将原型函数作为参数传递而不会丢失'this'上下文

Pet*_*uza 4 javascript function-prototypes prototype-programming

我通过原型在JavaScript中定义了一个" ".

func()第一次运行时,它可以工作,但是当它第二次被调用时,通过setTimeout,它会失败,因为这次它已经丢失了对象上下文,IE 不再引用该对象,而是现在引用窗口.

有没有办法可以在使用原型的同时克服这个问题?或者我是否需要使用闭包来定义" "?

function klass(){}

klass.prototype = {
  a: function() {
    console.log( "Hi" );
  },    
  func: function(){
    this.a();
    setTimeout( this.func, 100 );
  }
};

var x = new klass();
x.func();
Run Code Online (Sandbox Code Playgroud)

Tho*_*ing 7

用途Function.prototype.bind:

setTimeout( this.func.bind(this), 100 );
Run Code Online (Sandbox Code Playgroud)

来自Mozilla开发者网络:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

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;  
  };  
}  
Run Code Online (Sandbox Code Playgroud)