传递一个原型's函数作为参数而不丢失'this'上下文

Passing a prototype's function as parameter without losing the 'this' context

本文关键字:参数 上下文 this 函数 一个 原型      更新时间:2023-09-26

我在JavaScript中通过prototype定义了一个''。

第一次func()运行,它工作,但当它第二次调用时,通过setTimeout,它失败了,因为这次它已经丢失了对象上下文,即this不再引用对象,但现在引用window

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

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

使用Function.prototype.bind:

setTimeout( this.func.bind(this), 100 );

来自Mozilla Developer Network:

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;  
  };  
}  

你可以把它封装在一个函数中:

var self = this;  // reference the value of "this"
setTimeout( function() {self.func();}, 100 );

使用Function.prototype.bind,或者将setTimeout回调封装在自己的闭包中:

    func: function() {
        var self = this;
        self.a();
        setTimeout( function() {
            self.func();
        }, 100);
    }