function User() {
this.name = 'John';
setTimeout(function greet() {
console.log(`Hello, my name is ${this.name}`); // Hello, my name is
console.log(this); // window
}, 1000);
}
const user = new User();
作者:子非
链接:https://juejin.im/post/5ba24761e51d450e735e51f0
来源:掘金
为了方便解决这个问题,箭头函数就应用而生了。。。
function User() {
this.name = 'John';
setTimeout(() => {
'use strict'
console.log(`Hello, my name is ${this.name}`); // Hello, my name is John
console.log(this); // User {name: "John"}
}, 1000);
}
const user = new User();
作者:子非
链接:https://juejin.im/post/5ba24761e51d450e735e51f0
来源:掘金
总结:箭头函数在自己的作用域内没有自己的 this
,如果要使用 this
,就会指向定义时所在的作用域的 this 值。