2015-09-17 99 views
1

這個問題已經被提出並且提出的解決方案是使用'bind'。但是如何在這種情況下使用「綁定」?在原型中保留'this'上下文

var Fun = function(){ 
    this.count = 100; 
} 

Fun.prototype.f = function(){ 
    console.log("in f : " + this.count); 
} 

Fun.prototype.g = { 
    f : function(){ 
     console.log("in g-f : " + this.count); 
     // Is it possible to use 'bind' here to access 'this' of 'Fun' 
    } 
} 

fun = new Fun(); 
fun.f(); // Results - in f : 100 
fun.g.f(); // Results - in g-f : undefined 
fun.g.f.bind(fun)(); // Results - in f : 100 

是否有可能使用bind在這樣g.ffun.g.f()會給結果in f : 100

+1

@NEB:這是不可能的,那些是兩個不同的對象。 – zerkms

回答

6

是否可以使用「捆綁」這裏訪問'這個「樂」

沒有,因爲沒有this到要創建的第二f點綁定。你必須做的,而不是Fun

var Fun = function(){ 
    this.count = 100; 
    this.g = { 
     f: function() { 
      console.log("in g-f : " + this.count); 
     }.bind(this) 
    }; 
}; 

或者不綁定:

var Fun = function(){ 
    var t = this; 
    this.count = 100; 
    this.g = { 
     f: function() { 
      console.log("in g-f : " + t.count); 
     } 
    }; 
}; 

這並不涉及創建爲每個實例的新功能。現代瀏覽器引擎將在實例之間重用函數的代碼,即使創建了不同的函數對象

如果你想使從原型中使用f主體,這也是可能的:把g的原型,你所展示的,則:

var Fun = function(){ 
    var t = this; 
    var oldg = this.g; 
    this.count = 100; 
    this.g = { 
     f: function() { 
      return oldg.f.apply(t, arguments); 
     } 
    }; 
}; 

現在,如果後Fun.prototype.g.f變化實例已創建,則使用更新後的版本。但是,如果Fun.prototype.g被替換爲對新對象的引用,則會中斷。

+0

謝謝,我知道這個解決方案。但正如你所說,我試圖避免「爲每個實例創造新功能」。 – NEB

+0

@NEB:您基本上不能使用ES6的「代理」功能 - 這也可能涉及每個實例創建一個函數(以處理代理回調)。 –

+0

@NEB這是一個'非常優化'的場景,儘管它確實會產生一些輕微的簿記費用。這在使用'private'方法的代碼結構中很常見(或者需要維護一個特定的綁定)。除非處理{插入一些相關的值}數千個對象,否則我甚至不會眨眼睛這種方法做了我需要/希望它做的事情。 – user2864740

1

不,因爲fun.g是一個不同的對象。你所能做的就是在Fun的所有實例中放入不同的g對象,並在其中放入一個綁定函數f

function Fun() { 
    this.count = 100; 

    this.g = { 
    f: function() { 
     console.log("in g-f : " + this.count); 
    }.bind(this); 
    }; 
} 

Fun.prototype.f = function() { 
    console.log("in f : " + this.count); 
}; 
相關問題