原型功能bar
在Node.js環境中(其中bind
應該可用)在別處執行。我想this
內bar()
功能是我的對象實例:爲什麼在這個例子中原型函數的執行上下文(「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()
日誌undefined
和this
是不是我的實例?爲什麼執行上下文沒有被bind
調用改變?
除了什麼馬特說,每次通話時間'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