javascript - 在不丢失 'this' 上下文的情况下将原型(prototype)函数作为参数传递

标签 javascript function-prototypes prototype-programming

我正在通过原型(prototype)在 JavaScript 中定义一个“”。

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

有没有办法在我仍然使用原型(prototype)的同时克服这个问题?还是我需要改为使用闭包来定义“”?

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 开发者网络:

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

关于javascript - 在不丢失 'this' 上下文的情况下将原型(prototype)函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8610320/

相关文章:

javascript - 快速 Javascript 继承 : Understanding __proto__

javascript - 对象原型(prototype)上的 toString().call() 如何获取数组的类型

Javascript函数范围和查找父对象的属性

javascript - 如何将元素拆分为两个可连续的部分并在它们之间添加另一个元素

javascript - 使用 Moment js 库解析日期的问题

javascript - Bootstrap 下拉按钮问题

c - 带有 void* 参数的函数原型(prototype)

javascript - 将键和属性从对象推送到数组

c++ - 指向函数的指针怎么能指向内存中还不存在的东西呢?为什么原型(prototype)有不同的地址?

elf - 如何从ELF文件中提取函数原型(prototype)?