class会默认开启严格模式,严格模式下this的默认指向为undefined
class Fun {
constructor() {
let resolve = function() {
console.log('this', this)
};
resolve();
}
}
new Fun(); // this undefined
如上代码,在constructor里面用function定义了一个函数,函数打印this,然后直接调用该函数,正常情况该this应该是window,这里this的指向却是undefined。
我搜了相关信息才发现,class会默认开启严格模式,严格模式下this的默认指向为undefined。
这里使用箭头函数就好了,利用箭头函数this指向上下文的特点
class Fun {
constructor() {
let resolve = () => {
console.log('this', this)
};
resolve();
}
}
new Fun(); // this Fun