他们在那里做的是参考来函数没有叫它。
var x = foo; // Assign the function foo to x
var y = foo(); // Call foo and assign its *return value* to y
在JavaScript中,函数是对象。适当的对象。所以你可以传递给他们参考。
在这种特定情况下,他们正在设置handleServerResponse
作为XHR对象在就绪状态更改时使用的回调。 XHR对象将在执行ajax请求的过程中调用该函数。
一些例子:
// Declare a function
function foo() {
console.log("Hi there");
}
// Call it
foo(); // Shows "Hi there" in the console
// Assign that function to a varible
var x = foo;
// Call it again
x(); // Shows "Hi there" in the console
// Declare another function
function bar(arg) {
arg();
}
// Pass `foo` into `bar` as an argument
bar(foo); // Shows "Hi there" in the console, because `bar`
// calls `arg`, which is `foo`
它从一个事实,即函数对象自然如下,但它是值得的呼唤特别是有x
并在上面foo
之间没有神奇的联系;它们都只是指向相同功能的变量。除了它们指向相同的功能外,它们没有以任何方式链接,而改变它(例如指向另一个功能)对另一个功能没有影响。例如:
var f = function() {
console.log("a");
};
f(); // "a"
var x = f;
x(); // "a"
f = function() {
console.log("b");
};
f(); // "b"
x(); // "a" (changing `f` had no effect on `x`)
您可能想进一步解释,在执行'x = foo'后,您可以稍后执行'x()'。 –
@BryanOakley:我确实。 :-) –
也可能值得注意的是,如果您在将'foo'函数赋值给'x'后,'x'函数仍然是相同的(它不会继承赋值后的更改)。 – David