gpt4 book ai didi

javascript - 为什么 i 变量是 "copy"而不是对原始 i 的引用

转载 作者:行者123 更新时间:2023-12-02 17:55:25 25 4
gpt4 key购买 nike

我对下面的 JavaScript 代码有点困惑:

    // Because this function returns another function that has access to the
// "private" var i, the returned function is, effectively, "privileged."

function makeCounter() {
// `i` is only accessible inside `makeCounter`.
var i = 0;

return function() {
console.log( i++ );
};
}

// Note that `counter` and `counter2` each have their own scoped `i`.

var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2

var counter2 = makeCounter();
counter2(); // logs: 1
counter2(); // logs: 2

i; // ReferenceError: i is not defined (it only exists inside makeCounter)

我不明白为什么 countercounter2 中的 i 变量没有引用相同的 i 值?

我的理解是 counter 和 counter2 应该引用相同的函数,因为两者都被分配了相同的函数,并且函数是“引用数据类型”,不应该创建单独的副本。

另外,countercounter2怎么可能访问makecounter函数中设置的“私有(private)”值?

最佳答案

imakeCounter 本地的。

每次调用该函数时,您都会得到一个新的 i

该函数内部定义的匿名函数可以访问 i,因为它是在 makeCounter 内部定义的。

该函数已返回,因此它在 makeCounter 外部可用,但由于其定义位置,它仍然可以访问 i

My understanding is that counter and counter2 should reference the same function since both have been assigned the same function

他们没有被分配相同的职能。每次调用 makeCounter 时都会创建一个新函数。

关于javascript - 为什么 i 变量是 "copy"而不是对原始 i 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20999353/

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