const arto = { | |
name: 'Arto Hellas', | |
greet: function() { | |
console.log('hello, my name is ' + this.name) | |
}, | |
} | |
arto.greet(); // hello, my name is Arto Hellas | |
let greet = arto.greet; | |
greet(); // hello, my name is undefined | |
setTimeout(arto.greet, 1000); // // hello, my name is undefined | |
setTimeout(arto.greet.bind(arto), 1000); // hello, my name is Arto Hellas |
当通过引用调用方法,这个方法就失去了对原始 this 的引用,此时的 this 是 window
,所以 this.name
为 window.name
,也就是 undefined
。
# 通过 bind 方法保留原来的 this
setTimeout(arto.greet.bind(arto), 1000)
调用 bind 方法,传入 this,就可以保留原来的 this 了。这样 this 就会指向 Arto