调用不带括号的函数 returns 整个函数作为字符串

Calling a function without parentheses returns whole function as a string

我创建了一个这样的 JavaScript 对象:

var obj = {
  a: 10,
  b: 20,
  add: function(){
     return this.a + this.b;
  }
};

我以 obj.add 的形式执行函数,它 returns 整个函数作为字符串 a 如下所示:

function(){
  return this.a + this.b;
}

But later, I tried to call the function again, including the parentheses, like `obj.add()` and it returns the value `30`. I couldn’t figure out why I get such a different output upon calling the function with `obj.add` and with `obj.add()`. What is the main difference between calling an object’s function with parentheses and without parentheses?

没有括号,您正在检索对函数的引用,而不是调用(执行)函数

带括号,你正在执行函数。

function a() {
  return 2;
}

var b = a(); // called a, b is now 2;
var c = a; // c is referencing the same function as a
console.log(c); // console will display the text of the function in some browsers
var d = c(); // But it is indeed a function, you can call c(), d is now 2;

您没有使用 obj.add 执行函数,您只是在对象中查找它,而您所在的环境恰好将函数呈现为字符串。您可以通过添加括号来执行它。

没有括号,您实际上并没有调用任何东西,您也没有 return调用任何东西,它只是一个参考!

我猜你做过这样的事情

var result = ambes.add;

console.log(result);

并且不会调用该函数,它会记录 add 属性 的 实际内容,其中 函数,并且记录一个函数将记录该函数的字符串内容,而不是 return 你调用它时的内容。

非常简单:functionName 只是 return 函数体,而 functionName() 执行函数并且 return 是它的 return 值(或undefined,如果没有明确的 return)。当一个函数是一个对象 属性 时,同样的原则也适用,就像你 obj.add.

调用函数需要 () 因为它们是函数调用运算符。要执行函数,您始终需要包含括号。

当您调用 ambes.add 时,您正在 return 调用函数对象本身。如果您在 console.log() 内这样做或将其连接到字符串 JavaScript 上,函数定义将 return 作为一个完整的字符串来解释您收到的第一个输出。

您必须使用 () 调用 JavaScript 中的函数。

如果您不使用括号,您只是在引用函数,这在您希望将函数传递给另一个代码块以延迟执行的情况下非常有用。

在您的情况下,因为您希望立即调用 add,所以您应该确保使用 ()

obj.add();