在Javascript,Jquery中的类中调用类函数

时间:2012-05-24 11:52:30

标签: javascript

这是我正在尝试做的并且它不起作用,它显示的错误是:this.run不是一个函数。在线上(this.xId = window.setInterval('this.run()',2500);)

function(){

   this.run = function(){

      DO SOMETHING;

   }

   this.xId = window.setInterval( 'this.run()', 2500 );

}

可能是什么原因?

2 个答案:

答案 0 :(得分:1)

您需要匿名传递该功能:

this.xId = window.setInterval( function() { this.run() }, 2500 );

或者更好的是bind此函数与this上下文:

this.xId = window.setInterval( this.run.bind(this) , 2500 );

请注意,bind是在ECMA-262第5版中实现的,因此对于crossbrowser兼容性,您需要添加以下内容:

if (!Function.prototype.bind) {  
  Function.prototype.bind = function (oThis) {  
    if (typeof this !== "function") {  
      // closest thing possible to the ECMAScript 5 internal IsCallable function  
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");  
    }  

    var aArgs = Array.prototype.slice.call(arguments, 1),   
        fToBind = this,   
        fNOP = function () {},  
        fBound = function () {  
          return fToBind.apply(this instanceof fNOP  
                                 ? this  
                                 : oThis || window,  
                               aArgs.concat(Array.prototype.slice.call(arguments)));  
        };  

    fNOP.prototype = this.prototype;  
    fBound.prototype = new fNOP();  

    return fBound;  
  };  
}

答案 1 :(得分:0)

  • 首先,use a function reference rather than a string用于超时回调。使用字符串时this是全局对象,而不是可能提供它的内容。

  • 其次,缓存this的值。回调中的this可能与其外部的run不同(与function(){ var that = this; //cache "this" this.run = function(){ //DO SOMETHING; } this.xId = window.setInterval(function(){ that.run() },2500); } 附加的那个)。

    {{1}}
相关问题