我正在读这个 - http://learn.jquery.com/javascript-101/this-keyword/但有一个我不太明白的例子。
// A function being attached to an object at runtime.
var myName = "the global object";
var sayHello = function() {
console.log( "Hi! My name is " + this.myName );
};
var myObject = {
myName: "Rebecca"
};
var secondObject = {
myName: "Colin"
};
myObject.sayHello = sayHello;
secondObject.sayHello = sayHello;
sayHello(); // "Hi! My name is the global object"
myObject.sayHello(); // "Hi! My name is Rebecca"
secondObject.sayHello(); // "Hi! My name is Colin"
我都明白了,除了这两行:
myObject.sayHello = sayHello;
secondObject.sayHello = sayHello;
我们到底用它们做什么?我们为对象创建新键,并声明它们的值将是函数 sayHello,但我们省略括号是为了不显式调用函数?为什么我们需要它们?如果我们省略它们,我们会不会得到相同的结果,并且不会再次成为“在运行时附加到对象的函数”?