案例:打字游戏&贪吃蛇

普通函数和箭头函数的区别:

    1.普通函数/方法中的this, 谁调用就是谁
    2.箭头函数中的this, 是父作用域的this,不是调用者

例:

        let p = {
            name: "zhang",
            say: function () {
                console.log(this); // {name: "zhang ", say: ƒ}
            },
            // 因为没有将箭头函数放到其它的函数中, 所以箭头函数属于全局作用域
            // 在JS中只有定义一个新的函数才会开启一个新的作用域
            hi: () => {
                console.log(this); // Window 
            }
        }
        p.say();
        p.hi();

例:

function Person() {
            this.name = "zhang";
            this.say = function () {
                console.log(this); // Person
            }
            // 因为将箭头函数放到其它的函数中, 所以箭头函数属于其它函数(当前的其它函数就是构造函数)
            // 既然箭头函数属于构造函数, 所以箭头函数中的this就是构造函数的this
            this.hi = () =>{
                console.log(this); // Person
            }
        }
        let p = new Person();
        p.say();
        p.hi();

例:
注意点:
注意点: 箭头函数中的this永远都只看它所属的作用域的this
无法通过bind/call/apply来修改

        function Person() {
            this.name = "zhang";
            this.say = function () {
                console.log(this); // {name: "zs"}
            }
            this.hi = () =>{
                console.log(this); // Person
            }
        }
        let p = new Person();
        p.say.call({name: "zs"});
        p.hi.call({name: "zs"});

引申:优化案例代码

旧版本

    let self = this;
    this.timer = window.setInterval(function() {
      offset -= 20;
      if (offset <= -300) {
        self.bomb();
      }
      self.oDiv.style.top = offset + "px";
    }, 200);
    ⤵️ 优化代码

新版本

    this.timer = window.setInterval(() => {
      offset -= 20;
      if (offset <= -300) {
        self.bomb();
      }
      this.oDiv.style.top = offset + "px";
    }, 200);

点我预览 打字游戏

点我预览 贪吃蛇

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容