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

amb*_*bes 5 javascript function

我创建一个javascript对象如下代码:

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

我使用此代码执行该函数,obj.add它将整个函数作为字符串返回如下: -

function(){
     return this.a + this.b;
Run Code Online (Sandbox Code Playgroud)

但后来我尝试再次调用函数,包括括号之类obj.add(),它返回值30.在这里,我无法弄清楚为什么我得到这样的不同出来调用函数obj.addobj.add()?用括号调用对象函数和用括号括起来之间的主要区别是什么可以任何正文帮助?

Jua*_*des 5

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

使用括号,您正在执行该功能.

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;
Run Code Online (Sandbox Code Playgroud)