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
在JavaScript的class中,由于默认开启严格模式,函数内的this不再默认指向全局对象(在浏览器环境中通常是window),而是undefined。文章通过一个示例展示了在constructor内定义的传统函数中,this的指向是undefined。为解决这个问题,文章推荐使用箭头函数,因为箭头函数的this保持了外层作用域的指向,即指向class实例本身。

1832

被折叠的 条评论
为什么被折叠?



