Edw*_*uay 2 javascript functional-programming
我来自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
Run Code Online (Sandbox Code Playgroud)
谢谢@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"
});
Run Code Online (Sandbox Code Playgroud)
因为你在创建它时会返回一个不同的函数(在return你的第一行中没有调用的那个)... 这就是在其他调用上执行的函数.例如,这会给你1那么2:
var test = setup()(); // 1, 2
Run Code Online (Sandbox Code Playgroud)
你只是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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
313 次 |
| 最近记录: |