试问
你以为你懂了this
,那就试试,保证懵逼
1. 情景一
window.name = 'bob';
class A {
constructor() {
this.name = 'tom';
}
getName() {
console.log(this);
console.log(this.name + 111);
}
}
let a = new A();
let func = a.getName;
func();
在执行完
funcA()
后,请问输出啥?
你以为输出 ?
那你懂个锤子!!!正确输出如下:因为
class
使用严格模式,在严格模式下this
指向undefined
而非window
,所以在执行this.name
时又报上图错误。如果你还在纳闷为啥输出不是tom111
,那你真的很菜,往下看。
2. 情景二
// 非严格模式
window.name = 'bob'
let a = {
name: 'tom',
getName: () => {
console.log(this.name)
}
}
console.log(a.getName())
你以为输出 ?
tom
那你懂个锤子!!!正确输出是
bob
.
bob
不用太难过。 这里因为使用了箭头函数
箭头函数定义:箭头函数的this是在定义函数时绑定的,不是在执行过程中绑定的。简单的说,函数在定义时,this就继承了定义函数的对象。
可能读完了你还是不太理解为啥输出的是
bob
,我在用大白话讲一下。箭头函数中的this
取决于定义他的函数中的this。在情景二中,箭头函数是在对象中定义,不是函数! 箭头函数没有被函数包裹,所以this
取的是默认对象window
3. 情景三
// 非严格模式
window.name = 'bob'
let a = {
name: 'tom',
getName: function () {
console.log(this.name)
}
}
let func = a.getName;
func();
a.getName();
请问输出啥?
bob
tom
这次确实对了,因为这里的
this
是在执行环节中绑定的。func
在window
中执行所以绑定的是window
。.a.getName()
是在对象a中执行,所以this绑定为对象a。
总结
- 在严格模式下
this
指向undefined
,class
默认为严格模式。 - 箭头函数的
this
是在定义函数时就绑定的,如果没有外层函数则取默认window. - 除去以上的特殊情况,
this
才由执行过程中绑定。