Javascript中有和没有括号的调用函数的区别 [英] Difference of calling function with and without parenthesis in Javascript
问题描述
我正在处理javascript文件上传事件。我有以下功能和初始化程序:
I was handling a javascript file upload event. and I have the following function and following initializer:
初始化程序
$('#s3-uploader').S3Uploader({
allow_multiple_files: false,
before_add: progressBar.show,
progress_bar_target: $('.upload-progress-bar'),
remove_completed_progress_bar: false
}).bind("s3_upload_complete", function(e, content) {
console.log(content);
});
功能
var progressBar = {
show: function() {
$('.upload-progress-bar').show();
return true;
}
}
在初始化程序中,我注意到如果有差异,我
In the initializer, I noticed there is a difference if I do
before_add:progressBar.show
vs before_add:progressBar.show()
。使用括号,即使它被绑定到 before_add
选项,它也会被调用一次,而没有括号则不会。
before_add: progressBar.show
v.s. before_add: progressBar.show()
. With the parenthesis, it will be called once even if it is bound to the before_add
option, and without the parenthesis it will not.
我想知道我观察到的行为是否有任何解释。
I wonder if there are any explanation to the behaviour I observed.
推荐答案
使用括号调用方法因为括号的,该调用的结果将存储在before_add中。
With parenthesis the method is invoked because of the parenthesis, the result of that invocation will be stored in before_add.
如果没有括号,则将引用(或指针)存储到变量中的函数中。这样,只要有人调用before_add(),就会调用它。
Without the parenthesis you store a reference (or "pointer" if you will) to the function in the variable. That way it will be invoked whenever someone invokes before_add().
如果那不清楚的话;也许这会有所帮助:
If that didn't clear things up; maybe this will help:
function Foo() {
return 'Cool!';
}
function Bar(arg) {
console.log(arg);
}
// Store the >>result of the invocation of the Foo function<< into X
var x = Foo();
console.log(x);
// Store >>a reference to the Bar function<< in y
var y = Bar;
// Invoke the referenced method
y('Woah!');
// Also, show what y is:
console.log(y);
//Now, try Bar **with** parenthesis:
var z = Bar('Whut?');
//By now, 'Whut?' as already been output to the console; the below line will
//return undefined because the invokation of Bar() didn't return anything.
console.log(z);
如果您再看一下浏览器的控制台窗口,您应该看到:
If you then take a look at your browsers' console window you should see:
Cool!
Woah!
function Bar(arg)
Whut?
undefined
第1行是调用 Foo()的结果
,
第2行是调用 Bar()
via <$的结果c $ c> y ,
第3行是 y
的内容,
第4行是 var z = Bar('Whut?');
行的结果; Bar函数调用,
第5行显示调用 Bar()
并将结果赋值给 z
没有返回任何内容(因此: undefined )。
Line 1 is the result of invoking Foo()
,
Line 2 is the result of invoking Bar()
"via" y
,
Line 3 is the "contents" of y
,
Line 4 is the result of the var z = Bar('Whut?');
line; the Bar function is invoked,
Line 5 shows that invoking Bar()
and assigning the result to z
didn't return anything (thus: undefined).
这篇关于Javascript中有和没有括号的调用函数的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!