Dea*_*ean 36 javascript oop closures
我试图setTimeout()在JavaScript中的类函数内使用.本setTimeout()应该引发在同一类的另一种方法,所以我向它传递函数写成window.setTimeout("this.anotherMethod", 4000).这带来了问题:this引用调用Object,如果是的setTimeout()话window.如何使用enclosure返回对Class对象的引用?
myObject = function(){
this.move = function(){
alert(this + " is running");
}
this.turn = function(){
alert(this + " is turning");
}
this.wait = function(){
window.setTimeout("this.run" ,(1000 * randomNumber(1,5)));
}
this.run = function(){
switch(randomNumber(0,2)){
case 0:
this.move();
break;
case 1:
this.turn();
break;
case 2:
this.wait();
}
}
Run Code Online (Sandbox Code Playgroud)
}
Tik*_*vis 64
你可以这样做:
var that = this;
setTimeout(function () {
that.doStuff();
}, 4000);
Run Code Online (Sandbox Code Playgroud)
您还可以获得bind更简洁的代码(最初由@Raynos指出):
setTimeout(this.doStuff.bind(this), 4000);
Run Code Online (Sandbox Code Playgroud)
bind是一个标准的库函数,用于完全符合这种编码模式(即从this词汇上捕获).
您还可以将函数绑定到范围.
setTimeout(this.run.bind(this) ,(1000 * randomNumber(1,5)));
警告Function.prototype.bind是ES5
this 正如您所发现的那样,在javascript中可能会出现问题.
我通常通过this在对象内部别名来解决这个问题,这样每当我需要一个引用回到包含对象时我就可以使用别名.
MyObject = function ()
{
var self = this;
// The rest of the code goes here
self.wait = function(){
window.setTimeout(self.run ,(1000 * randomNumber(1,5)));
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
class A{
setTimeout(()=>{
// here this != undefined because of arrow function
},500);
}
Run Code Online (Sandbox Code Playgroud)