调用不带括号的函数将整个函数作为字符串返回 [英] Calling a function without parentheses returns whole function as a string

查看:51
本文介绍了调用不带括号的函数将整个函数作为字符串返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个JavaScript对象,如下所示:

I created a JavaScript object like this:

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

我以 obj.add 的形式执行该函数,它以字符串形式返回整个函数,如下所示:

I executed the function as obj.add and it returns the whole function as string a like this:

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?

推荐答案

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

Without parentheses, you're retrieving a reference to the function, you are not calling (executing) the function

在括号中,您正在执行该函数.

With parentheses, you're executing the function.

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;

这篇关于调用不带括号的函数将整个函数作为字符串返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆