什么是this关键字
在JavaScript的函数中,可以通过this访问调用当前函数的对象。所以:
- 对于函数,this是window对象(浏览器环境)。
- 对于方法,this是该方法所属的对象。
function foo() {
// 由于foo是普通函数,所以这里this是window对象
console.log(this);
}
let bar = {
name: 'tom',
sayHi: function() {
// 由于sayHi是对象bar的方法,所以这里this是bar对象
console.log(this.name, 'say hi.');
},
};
this关键字的问题
我们现在知道,函数中的this是window对象,方法中的this是该方法所属的对象。那么,方法内嵌套的函数的this是什么呢?还是window对象!
let bar = {
name: 'tom',
sayHi: function() {
function foo() {
// foo函数是嵌套在sayHi方法内的函数,这里的this是什么呢?
console.log(this.name, 'say hi.');
}
foo();
},
};
上面例子中,foo
函数就是一个普通函数,所以foo
函数里面的this是window对象。所以上面代码就有bug。这就是JavaScript中this关键字的问题。
有很多方法可以解决这个问题。ES6中推出箭头函数后,一般我们用箭头函数来解决这个问题。
let bar = {
name: 'tom',
sayHi: function() {
let foo = () => {
console.log(this.name, 'say hi.');
}
foo();
},
};
上面代码中,foo
函数依然是嵌套在方法内的函数,但是由于foo
函数是箭头函数,箭头函数中的this,会继承嵌套它的函数(sayHi
)的this,所以就解决了这个问题。
在ES6之前,可以用bind
、call
或者apply
这些可以手动绑定函数的this对象的方法来解决这个问题。不过有了箭头函数后,一般都是用箭头函数了。
网友评论