JavaScript:调用带括号的函数返回整个函数作为字符串 [英] JavaScript: calling a function with out parenthesis return's whole function as string
问题描述
我创建了一个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 $ c $调用函数c>和
obj.add()
?调用一个带有括号的对象函数和带括号的外部函数之间的主要区别是什么?任何正文都可以帮助吗?
您正在检索对该函数的引用,而不是调用(执行)该函数。
使用括号,您正在执行该函数。
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屋!