更新时间:2022-12-14 19:48:21
使用括号调用方法因为括号的,该调用的结果将存储在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 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).