我来自C#/ PHP并试图了解Javascript的想法,即函数是变量/对象,并且具有准构造函数等。
任何人都可以解释为什么以下代码的功能,即:
test
?test
?代码:
var setup = function () {
console.log(1);
return function() {
console.log(2);
};
};
var test = setup(); // 1
test(); // 2
test(); // 2
test(); // 2
感谢@thejh @Justin所以函数返回一个与第一个完全不同的完全不同的函数(我想第二个函数作为第一个函数的构造函数),如果我发表评论,那就更清楚了:
$(document).ready(function() {
var setup = function () {
console.log(1);
// return function() {
// console.log(2);
// };
};
var test = setup(); // 1
test(); // "test is not a function"
test(); // "test is not a function"
test(); // "test is not a function"
});
答案 0 :(得分:5)
因为你从创建它时调用的函数返回不同的函数(return
中的那个,你没有在第一行调用的那个)... 是在其他调用上执行的内容。例如,这会为您提供1
,然后2
:
var test = setup()(); // 1, 2
答案 1 :(得分:5)
你只是第一次打电话给setup()
。调用后,它返回的新函数将分配给test
。从那以后,你称之为新功能:
// calls setup which logs 1 and returns a new function.
// setup also returns a new function and assigns that new function to test.
var test = setup();
// test now is the equivalent of var test = function(){ console.log(2); };
// call the new function that setup returned which logs 2
test();
// and again
test();
// and again
test();
答案 2 :(得分:1)
在第一次对setup()进行测试时,你正在执行整个函数,因此运行console.log(1)
,然后返回一个新函数。
现在,您将第一个函数的返回值指定为运行console.log(2)
的下一个函数,所以现在测试返回函数的引用。
您的后续调用只运行运行console.log(2)
答案 3 :(得分:1)
调用setup()
打印1
并返回对该匿名函数的引用。打电话打印2
。
答案 4 :(得分:1)
想象一下,而不是
var setup = function () {
console.log(1);
return function() {
console.log(2);
}
}
此等效OOP syntax
var setup = new Function("\
console.log(1);\
return new Function(\"\
console.log(2);\
\");\
");
var test = setup(); // 1
test(); // 2
test(); // 2
test(); // 2
我认为你现在应该对此更加熟悉。
答案 5 :(得分:1)
您执行setup()
时执行以下两行:
console.log(1);
function() { console.log(2); }
当你执行test()
时,你实际上调用了你创建的函数,因此你记录了“2”
JS是一种函数式语言,你必须看到像第一个公民对象这样的函数。