funtion 和 箭头函数 的 this 指向

73 阅读1分钟

this 指向

箭头函数是 ES6 新增的。

对于其 this 指向,可以简单的认为: 它没有自己的this对象,内部的this就是定义时上层作用域中的this

window & function

在 funtion 内部添加 eat 方法

function Student() {
    this.name = "a";
    this.eat = () => {
        console.log("student eat...", this);
    }
}

image.png 在原型链上添加 eat 方法:

Student.prototype.eat = () => {
    console.log("student eat...", this);
}

image.png 我们知道箭头函数没有 this ,它会往作用域链寻找。

第一个(funtion)很明显 this 指的就是 function 第二个它是直接在全局环境下创建,this 指的 window

切换 funtion

然后我们将箭头函数改成 function 来声明。

主要更改原型链上的 eat 方法:

Student.prototype.eat = function () {
    console.log("student eat...", this);
}

输出结果:student eat... Student {name: 'a'} [变了]

验证一下

 function Person(person_name) {
    "use strict";
    const _out_this = this;
    this.person_name = person_name;

    this.eat = function () {
        const _in_this = this;
        const a = () => {
            console.log(" => in eat funtion ", this === _in_this, this === _out_this); // true true
        }
        a();
        console.log("eat funtion ", this === _out_this); // true
    }

    this.run = () => {
        console.log(" => in Person ", this === _out_this); // true
    }
}