2

如何在使用 javascript 创建对象时执行函数

运行以下代码

 var y = [] ;
 var x = [[1,2,3] , [4,5,6] , [7,8,9]]
 for (var i = 0 ; i < 3 ; i++){
     y.push({name :'MyName' , value:function(){return x[i]} }) ; 
 }

 console.log(y) ;  

将生成以下对象

{name : 'MyName' , value : function (){return x[i]}

问题

我怎样才能执行这个具有这个的对象函数:

{name : 'MyName' , value : function (){return [1,2,3]}

我试过eval()没用

这是我的jsFiddle

对于那些问WHY你这样做的人吗?我这样做是因为 object 将按值复制,所以我最终会让我全部object.Value等于 X[2] ;

4

2 回答 2

2

它是一个奇怪的代码。我不确定您要达到的目标。但是您遇到的问题i是在整个循环中都在递增。因此,当您最终调用该函数时,其值为i3,因此超出了x数组的范围。你可以像这样修复它:

var y = [] ;
var x = [[1,2,3] , [4,5,6] , [7,8,9]]
for (var i = 0 ; i < 3 ; i++){
    y.push({
        name :'MyName',
        index: i,
        value:function(){return x[this.index]; } 
    }) ; 
}

console.log(y[0].value()); 

或者,如果您不明确需要执行函数:

var y = [] ;
var x = [[1,2,3] , [4,5,6] , [7,8,9]]
for (var i = 0 ; i < 3 ; i++){
    y.push({
        name :'MyName',
        value: x[i]
    }) ; 
}

console.log(y[0].value); 
于 2013-02-11T17:21:39.320 回答
0

要成功地将这些对象添加到数组中,您需要在 y.push() 语句上创建一个闭包。闭包将确保变量 x[i] 在调用时可用于 value() 函数。

The code below defines the 'addItem()' function which closes over the 'value()' function of the object creating a self contained environment. This means the 'value()' function will still have access to the variables defined or passed within the 'addItem()' function even after the 'addItem()' function has finished.

var i = 0
var y = [] ;
var x = [[1,2,3] , [4,5,6] , [7,8,9]];

function addItem(item) {
    y.push({
        name: 'MyName', 
        value: function () {
            return item;
        }
    });
}

for ( ; i < 3 ; i++) {
    addItem(x[i]);
}

console.log(y);
/*
[ { name: 'MyName', value: [Function] },
  { name: 'MyName', value: [Function] },
  { name: 'MyName', value: [Function] } ]
*/
console.log(y[0].value()); // [1, 2, 3]
console.log(y[1].value()); // [4, 5, 6]
console.log(y[2].value()); // [7, 8, 9]

You can also achieve the same thing using an anonymous function within the loop but I choose not to do this as that would have created a new function each time you went around the for loop.

于 2013-02-11T18:06:31.733 回答