传递到函数队列时保留对象状态 (Javascript)

Preserve Object State when passed into queue of functions (Javascript)

一直在尝试找出一种方法来在推入函数时保留我的对象状态。示例代码如下:

window.queue = window.queue || [];

var some_data = {
    "object_number":1
}

queue.push(function(){console.log("1:",some_data)});

var some_data = {
    "object_number":2
}

queue.push(function(){console.log("2:",some_data)});

// Code I Cannot Change
for (var i = 0; i < queue.length; i++) {
    queue[i]();
}

队列执行结果为:

1: {object_number: 2}
2: {object_number: 2}

你能看到当队列被解析时(我无法更改这段代码 - 它是由其他人控制的)它如何查找 'some_data' 的最新版本吗?

知道如何保存对象传入时的状态吗?期望的结果是:

1: {object_number: 1}
2: {object_number: 2}

谢谢!

您可以使用以下变体,每次都会使用局部变量 (value) 创建 closure

var some_data = {
    "object_number":1
}

queue.push(((value) => () => console.log("1:",value))(some_data));

var some_data = {
    "object_number":2
}

queue.push(((value) => () => console.log("2:",value))(some_data));

在这种情况下,覆盖some_data后,value不会改变,因为它是一个单独的变量。但注意改变some_data的内容也会改变value的内容(那么可能你需要在每个push之前复制some_data):

var some_data = {
    "object_number":1
}

queue.push(((value) => () => console.log("1:",value))(some_data));

var some_data = {
    "object_number":2
}

queue.push(((value) => () => console.log("2:",value))(some_data));

some_data.object_number = 1;

for (var i = 0; i < queue.length; i++) {
    queue[i]();
}

// 1: { object_number: 1 }
// 2: { object_number: 1 }