gpt4 book ai didi

javascript - 为什么这个原始变量通过引用而不是值传递给函数?

转载 作者:行者123 更新时间:2023-11-27 22:31:00 25 4
gpt4 key购买 nike

这涉及到一些 Angular,但我认为这主要是一个纯粹的 javascript 范围问题。我有一个指令在我的页面上被调用几次,带有 ng-repeat 。当第一次调用它时,我设置了变量 current_index等于单元页面上标签的索引号,如下所示:

var current_index = scope.$eval(attrs.index);

然后我将其传递给一个延迟半秒的函数。

    g.append("g")
.transition()
.duration(500) //Half second delay
.on("start", function(){
tick(current_index); //Passing the current_index variable
});

但是,当为标记的每个实例调用此函数时,current_index始终等于调用的最后一个索引的编号(例如:如果我有 3 个与我的指令相对应的标签,并在延迟的函数中打印 console.log(current_index); ,它将打印 2 3 次,而不是0, 1, 2 .

function tick(index){
console.log(index);
}
// Prints 2, 2, 2

但是,如果我引入一个新变量,a ,并将其设置为等于 current_index ,并将其传递到它按预期工作的函数中。

var current_index = scope.$eval(attrs.index);
var a = current_index

g.append("g")
.transition()
.duration(500) //Half second delay
.on("start", function(){
tick(a); //Passing the a variable
});


function tick(index){
console.log(index);
}
// Prints 0, 1, 2

看起来current_index作为对象传递,并且 a作为原语传递,但两者都返回 number当我执行typeof时功能。这是怎么回事?

最佳答案

这可能会令人困惑。但请记住,您不是在此处传递 current_index ,而是定义一个具有闭包的函数,并且通过该闭包可以访问父作用域中的变量 current_index 。

.on("start", function(){
tick(current_index); // you have access to this because of the closure
});

因此,如果您更改 current_index 的值,无论您在其中创建的匿名函数执行时 current_index 是什么,这都将传递给tick()。

这就是为什么在 for 循环内创建函数是危险的原因之一。您需要使用立即调用的函数,该函数将当前索引作为参数,并返回您想要 .on 执行的函数。或者您可以绑定(bind)您传递的函数:

.on("start", function(boundIndex){
tick(boundIndex); // now the value at the time of binding is bound
}.bind(null, current_index);

关于javascript - 为什么这个原始变量通过引用而不是值传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39585143/

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