如何在构造函数中使用setTimeout

时间:2016-04-04 14:32:29

标签: javascript

我有一个构造函数:

function Domino() {

var self = this;
this.myElement = $("#smth");

this.rotation = 0;
this.rotateFor = function (deg, scl) {
    this.rotation += deg;
    this.scale = scl;
    this.myElement.find(".domino-view").css({
        transform: "rotate(" + self.rotation + "deg)  scale(" + self.scale + ")"
    });
};

我想在rotateFor设置超时。我试过这个:

this.rotateFor = function (deg, scl) {
    this.rotation += deg;
    this.scale = scl;
    this.myElement.find(".domino-view").css({
        transform: "rotate(" + self.rotation + "deg)  scale(" + self.scale + ")"
    });
}
this.start = function(){
self.timeout = setTimeout(function(){this.rotateFor()}, 5000)

}

然后我这样称呼它:something.start(),但它仍然不起作用。如何在此构造函数中设置超时?

3 个答案:

答案 0 :(得分:0)

您正在使用selfthis中创建实例变量和setTimeout,而不会引用正确的对象实例。

function Domino() {

   var self = this;
   this.myElement = $("#smth");

   this.rotation = 0;
   this.rotateFor = function (deg, scl) {
       this.rotation += deg;
       this.scale = scl;
       this.myElement.find(".domino-view").css({
           transform: "rotate(" + self.rotation + "deg)  scale(" + self.scale + ")";
       });
   };

   this.start = function(){
      this.timeout = setTimeout(function(){
          // Here is where the self variable benefits you:
          self.rotateFor();
      }, 5000);
   }
 }

答案 1 :(得分:0)

首先,self不存在于任何地方(在该范围内)。其次,setTimeout函数中的this不引用当前对象。您还需要在正确的上下文中调用rotateFor

使用类似:

this.start = function(deg,scl){
    var self = this; //Must specify what self is.
    this.timeout = setTimeout(function(){ //This outside (self also works since we defined it)
          self.rotateFor(deg,scl); 
    }, 5000);
}

如果要在构造函数中启动超时,可以执行以下操作:

function Domino() {

var self = this;
this.myElement = $("#smth");

this.rotation = 0;
this.rotateFor = function (deg, scl) {
    this.rotation += deg;
    this.scale = scl;
    this.myElement.find(".domino-view").css({
        transform: "rotate(" + self.rotation + "deg)  scale(" + self.scale + ")"
    });
};
setTimeout(function(){ 
    self.rotateFor(<p1>,<p2>); //Parameters needed
}, 5000);

答案 2 :(得分:0)

你需要绑定它:

setTimeout(function(){this.rotateFor()}.bind(this), 5000);