为什么Javascript函数在实例化时的行为与执行时不同? [英] Why does a Javascript function act differently upon instantiation than execution?
问题描述
我来自C#/PHP,试图弄清Javascript的观点,即函数是变量/对象,并且具有类似的构造函数,等等.
I'm coming from C#/PHP and trying to get my head around Javascript's idea that functions are variables/objects and have quasi constructors, etc.
任何人都可以解释以下代码为何起作用,即:
Can anyone explain why the following code functions as it does, namely:
- 为什么实例化变量/函数
test
时不显示"2"? - 为什么执行变量/功能
test
时不显示"1"?
- Why isn't "2" displayed when instantiating the variable/function
test
? - Why isn't "1" displayed when executing the variable/function
test
?
代码:
var setup = function () {
console.log(1);
return function() {
console.log(2);
};
};
var test = setup(); // 1
test(); // 2
test(); // 2
test(); // 2
已添加:
感谢@thejh @Justin,因此该函数返回的完全不同的函数与第一个函数无关(我当时认为第二个函数是第一个函数的一种构造函数),如果我将其注释掉,那就更清楚了:
added:
Thanks @thejh @Justin so the function is returning a completely different function that has nothing to do with the first (I was thinking of the second function as a kind of constructor of the first), if I comment it out, it's clearer:
$(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"
});
推荐答案
您仅在第一次呼叫setup()
.一旦调用,它将返回的新函数分配给test
.从那里开始,您要调用该新函数:
You're only calling setup()
the first time. Once it is called, the new function it returns is assigned to test
. From there on, you're calling that new function:
// 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();
这篇关于为什么Javascript函数在实例化时的行为与执行时不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!