2013-02-18 25 views
2

原型功能bar在Node.js環境中(其中bind應該可用)在別處執行。我想thisbar()功能是我的對象實例:爲什麼在這個例子中原型函數的執行上下文(「this」)是錯誤的?

var Foo = function (arg) { 
    this.arg = arg; 

    Foo.prototype.bar.bind(this); 
}; 

Foo.prototype.bar = function() { 
    console.log(this); // Not my object! 
    console.log(this.arg); // ... thus this is undefined 
} 

var foo = new Foo(); 
module.execute('action', foo.bar); // foo.bar is the callback 

...爲什麼bar()日誌undefinedthis是不是我的實例?爲什麼執行上下文沒有被bind調用改變?

+1

除了什麼馬特說,每次通話時間'Foo'你會綁定一個不同的'this'。如果您將該函數作爲'foo.bar'調用,爲什麼要使用'bind'呢?另外,'this'不是「context」,它是一個特殊的函數值,是它們[執行上下文]的一個參數(http://www.ecma-international.org/ecma-262/5.1/#sec-10 ),以及所有其他變量和作用域鏈。 – RobG 2013-02-18 22:14:48

回答

6

Function.bind返回一個值 - 新綁定的函數 - 但您只是放棄該值。 Function.bind不會更改this(即其調用上下文),也不會更改其參數(this)。

是否有另一種方法可以獲得相同的結果?

做它的構造函數裏面其實是錯誤的,因爲bar生活在Foo.prototype,所以結合的Foo任何一種情況,將打破this所有其他Foo.bar來電!綁定它,你意味着它:

module.execute('action', foo.bar.bind(foo)); 

或者 - 甚至更簡單 - 不要在原型都定義bar

var Foo = function (arg) { 
    this.arg = arg; 

    function bar() { 
     console.log(this); 
     console.log(this.arg); 
    } 

    this.bar = bar.bind(this); 
}; 

var foo = new Foo(); 
module.execute('action', foo.bar); 
+0

也就是說,我需要分配返回值?有另一種方法可以獲得相同的結果嗎?我不喜歡重新分配函數的想法... – gremo 2013-02-18 22:11:21

+0

我需要一些時間來充分理解您的答案,同時......非常感謝您! – gremo 2013-02-18 22:35:32

相關問題