更令人困惑的部分实际上是关于第三个例子,但让我回答你关于第二个例子的具体问题:
问题是为什么(object.getName)(); 会打印"My object" 而不是像第三个那样打印"The window"?
想想 JavaScript 如何解析你的代码片段:
object // This is the reference to the object you've made. No surprises here
object.getName // A reference to the function `getName`, with `this` bound to `object`
(object.getName) // This is the same thing as #2. The parens aren't important here
object.getName(); // Invoking the function, as you normally would
(object.getName)(); // Strange syntax, but just invoking the function all the same
但是当“窗口”被打印出来的时候呢?
这是更令人困惑的部分。
(object.getName = object.getName)(); // Things start to go strange here
这部分是因为赋值 (=) 运算符,也是因为 JavaScript function binding (this keyword) is lost after assignment。
当您引用函数对象然后将该引用分配给任何内容时,它会作为“值类型”而不是“引用类型”传递。这会删除 this 指针,除非您手动将其绑定回来。见the documentation for the this keyword, when calling a function as an object method:
当函数作为对象的方法被调用时,其this 被设置为调用该方法的对象。
通过修改您的示例,这意味着什么可能会变得更加清楚:
var name = "The window";
var object = {
name: "My object",
getName: function() {
console.log(this); // See what `this` is bound to
return this.name;
}
}
object.getName(); // Prints `Object {name: "My object"}`
(object.getName)(); // Also prints `Object {name: "My object"}`
var func = object.getName;
func(); // Prints `Window`
(object.getName = object.getName)(); // Also prints `Window`
如果您尝试将函数作为回调传递给其他函数,您会注意到相同的行为:
function test(callback) {
callback();
}
test(object.getName); // Prints `Window`
但是,如果基础对象在您调用它时仍被绑定,那么您将看到正常的对象行为:
function test(obj) {
obj.getName();
}
test(object); // Prints `Object {name: "My object"}`
其他有趣或有用的行为
执行分配不会破坏原始对象。即使您在其他一些参考上得到了this,object 仍然完好无损:
(object.getName = object.getName)(); // Prints `Window`
object.getName(); // Prints `Object {name: "My object"}`. It didn't break
如果您将函数引用分配回对象的不同属性,您会看到this 在新属性上被正确分配。这是因为重要的部分是您是否在调用函数时指定了基础对象:
var temp = object.getName;
temp(); // Prints `Window`
object.somethingElse = temp;
object.somethingElse(); // Prints `Object {name: "My object"}`. `this` is correctly bound
如果你从一个对象中提取一个函数并将其粘贴到一个完全不同的对象上,那么它仍然可以工作,但this 将绑定到新对象。
Object prototypes 依靠这种行为来施展魔法。
var basketball = {
name: "Sports equipment?!",
}
basketball.doStuff = object.getName;
basketball.doStuff(); // Prints `Object {name: "Sports equipment?!"}`
如果由于某种原因您在没有绑定this 的情况下获得了对您的函数的引用,您仍然可以更正它,只要您有对原始对象的引用:
var temp = object.getName;
temp(); // Prints `Window`
var temp2 = temp.bind(object);
temp2(); // Prints `Object {name: "My object"}` because you bound `this`
temp.apply(object); // Also prints `Object {name: "My object"}`