繁体   English   中英

从Javascript,Jquery中的类中调用Class函数

[英]Calling a Class function from within a class in Javascript, Jquery

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

function(){

   this.run = function(){

      DO SOMETHING;

   }

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

}

可能是什么原因 ?

您需要为此传递匿名函数:

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

或者更好的方法是将此函数与this上下文绑定

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

请注意, bind是在ECMA-262,第5版中实现的,因此,为了实现跨浏览器的兼容性,您需要添加以下内容:

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;  
  };  
}
  • 首先,对于超时回调, 使用函数引用而不是字符串 使用字符串时的this是全局对象,而不是可能提供的对象。

  • 其次,缓存this的值。 回调中的this可能与外部的this不同(后者与run )。

     function(){ var that = this; //cache "this" this.run = function(){ //DO SOMETHING; } this.xId = window.setInterval(function(){ that.run() },2500); } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM