我正在读这篇文章 - 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,但我们省略括号以便不显式调用该函数?为什么我们需要它们?如果我们省略它们,我们不会得到相同的结果,并且不会再次成为“在运行时附加到对象的函数”吗?
最佳答案
We create new keys to the objects and state that their values will be the function sayHello,
是的
but we omit the parenthesis in order not to explicitly call the function?
是的。如果您调用了该函数,那么您将分配函数调用的返回值而不是函数本身。
If we omit them, won't we get the same result
如果省略这两行,则 myObject.sayHello
将是undefined
当您尝试调用 undefined()
时,您会收到错误消息.
关于javascript - 函数作为对象和函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15699193/