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 值。