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

2024-04-01

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

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

我将函数执行为obj.add它将整个函数作为字符串 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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

调用不带括号的函数将整个函数作为字符串返回 的相关文章

随机推荐