var prop = 100;
function Parent() {
this.prop = ‘parent’;
}
Parent.prototype.get = function() {
alert(this.prop);
};
Parent.prototype.show = function() {
//this.get()
setTimeout(()=>this.get(), 100);
};
var child = new Parent();
child.show(); // ?
1.将bind换成call,apply也会导致立即执行,延迟效果会失效
window.setTimeout(this.declare.bind(this), 2000);
2.使用es6中的箭头函数,因为在箭头函数中this是固定的。
// 箭头函数可以让setTimeout里面的this,绑定定义时所在的作用域,而不是指向运行时所在的作用域。
// 参考:箭头函数
window.setTimeout(() => this.declare(), 2000);