2013-07-08 33 views
3

方面也有一些是我不明白的JavaScript砸开一个样本问题的基本情况:绕过功能包括其在JavaScript

a = function() { 
     this.b = 5; 
    } 

    a.prototype.c = function() { 
     alert(this.b); 
    } 

    var d = new a(); 
    var e = d.c; // how do I save a ref to the method including the context (object)?? 

    d.c(); // 5 -> ok 
    e(); // undefined -> wtf?? 

那么,为什么被调用的函数没有它的上下文最后一个例子?我怎样才能在上下文中调用它?

预先感谢:-)

回答

5

d.c就像是一个未结合的实例方法。您可以使用Function.prototype.bind创建绑定到d新功能(第一个参数.bindthis参数):

var e = d.c.bind(d); 

或致电ed作为this参数:

e.call(d); 
2

你需要使用对象调用方法来获取正确的上下文。所以:

var e = function() { return d.c(); }; 

在新的浏览器可以使用bind method做同样的:

var e = d.c.bind(d); 

在jQuery中,例如存在proxy method,你可以在旧的浏览器也使用:

var e = $.proxy(d.c, d); 
1

这是关于解决this价值。这是通过以下方式解决:

myObject.something();//this in something is myObject 
window.something();//this is window 
button.onClick=function();//this when button is clicked is button 

如何解决它已经给出,它使用的setTimeout

var test = function() { 
    var me = this;// set reference to this 
    this.sayAgain=function(){ 
    console.log("Hi, I am "+me.toString()); 
    } 
} 
test.prototype.toString=function(){ 
    return "test"; 
} 

test.prototype.say = function() { 
    console.log("Hi, I am "+this.toString()); 
} 

var t = new test(); 
setTimeout(t.say,50);//=window passing functon without ref to this 
setTimeout(function(){ 
    t.say(); 
},150);//=test passing ref with function 
setTimeout(t.sayAgain,200);//=test using me as the saved this context 

第二种超时传递一个closure在下面的例子中传递回调像一个常见的错误setTimeout,如果你打算通过说回调数百次,但只创建了几个测试对象实例,那么最后一个(sayAgain)的执行会稍微好一些。

这是因为您在创建测试实例时创建闭包,但在传递sayAgain作为回调时不会创建封闭,如果创建了很多测试实例并且不会多次传递say,那么请将this.me和this.sayAgain从功能体并通过say作为封闭。

您可以使用Function.prototype.bind,但它不支持在IE < 8中,我不确定它是否会像我的示例中使用t.say那样创建闭包。