将原型函数作为参数传递而不会丢失'this'上下文 [英] Passing a prototype's function as parameter without losing the 'this' context

查看:109
本文介绍了将原型函数作为参数传递而不会丢失'this'上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是通过原型在JavaScript中定义''。

I'm defining a 'class' in JavaScript by means of prototype.

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

The first time func() runs, it works, but when it's called the second time, through a setTimeout, it fails because this time it has lost the object context, I.E. this doesn't reference the object anymore but now references window.

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

Is there a way I can overcome this while still using prototype? or do I need instead to use closures to define a 'class'?

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

From Mozilla Developer Network:

< a href =https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind> 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;  
  };  
}  

这篇关于将原型函数作为参数传递而不会丢失'this'上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆