gpt4 book ai didi

javascript - 为什么 Javascript 函数在实例化和执行时的行为不同?

转载 作者:行者123 更新时间:2023-12-04 01:08:10 25 4
gpt4 key购买 nike

我来自 C#/PHP,并试图了解 Javascript 的想法,即函数是变量/对象并具有准构造函数等。

谁能解释为什么下面的代码会这样运行,即:

  1. 为什么实例化变量/函数test时不显示“2”?
  2. 为什么执行变量/函数test时不显示“1”?

代码:

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"

});

最佳答案

您只是第一次调用 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();

关于javascript - 为什么 Javascript 函数在实例化和执行时的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4462497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com