JavaScript:调用带括号的函数返回整个函数作为字符串 [英] JavaScript: calling a function with out parenthesis return's whole function as string

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

问题描述

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

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

我用这段代码执行函数 obj.add ,它返回整个函数的字符串,如下所示: -

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

但是后来我再次尝试调用该函数,包括像 obj这样的括号。 add(),它返回值30.在这里,我不明白为什么我得到这样不同的出来,用 obj.add obj.add()?调用一个带有括号的对象函数和带括号的外部函数之间的主要区别是什么?任何正文都可以帮助吗?

解决方案

您正在检索对该函数的引用,而不是调用(执行)该函数。

使用括号,您正在执行该函数。



function a(){return 2;} var b = a(); //叫做a,b现在是2; var c = a; // c引用与aconsole.log(c)相同的函数; // console将在一些browsersvar中显示函数的文本d = c(); //但它确实是一个函数,你可以调用c(),d现在是2;


I create a javascript Object as below code:

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

i executed the function with this code obj.add and it return the whole function as string like this:-

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

but later i try by call the function again including the parenthesis like obj.add() and it return the value 30. Here i couldn't figure out why i get such different out put upon calling the function with obj.add and obj.add()? What is the main difference between calling an objects function with parenthesis and with out parenthesis Can any body help??

解决方案

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;

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

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