名词解释
this代表当前执行代码的环境对象。
this不能在执行期间被赋值,并且在每次函数被调用时this的值也可能会不同。
全局环境
全局环境中this都指向全局对象(Window)
console.log(this); // Window
函数(运行内)环境
在函数内部,this的值取决于函数被调用的方式。
function函数
非严格模式下,this 的值默认指向全局对象,当作为属性或方法调用时指向被执行环境对象。
let f1 = function () {
console.log(this);
};
document.onclick = f1;
f1(); // Window
document.onclick(); // #document
箭头函数
this与封闭词法环境的this保持一致。
let f2 = () => {
console.log(this);
};
document.onclick = f2;
f2(); // Window
document.onclick(); // Window
bind、call、apply
bind方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用;
call、apply方法与bind方法类似,但无需再次调用。
this.x = 9; // this 指向全局的 "window" 对象
let module = {
x: 81,
getX: function() {
console.log(this.x);
},
_getX: () => {
console.log(this.x);
}
};
module.getX(); // 81
module._getX(); // 9
// 尝试使用call来设定this
module.getX.call(this); // 9
module._getX.call(module); // 9
// 使用bind来设定this
let getX = module.getX.bind(this),
_getX = module._getX.bind(module);
getX(); // 9
_getX(); // 9
由此可见,如果将this传递给call、bind、或者apply,function内部this将被改变,但箭头函数将忽略所传this。
构造函数
当一个函数用作构造函数时,它的this被绑定到正在构造的新对象。
class Test {
constructor() {
this.num = 5;
this.getNum = function () {
console.log(this.num);
};
}
}
let t = new Test();
t.getNum(); // 5
总结
function:谁调用this便指向谁。
箭头函数:本身没有this,其this继承声明时所在环境对象。
详情请查看MDN-this。