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);
博客围绕JavaScript代码展开,涉及变量定义、函数创建。提到将bind换成call、apply会使延迟效果失效,还介绍使用ES6箭头函数解决setTimeout里this绑定问题,让this绑定定义时作用域。
90

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



