2

因此,如果我创建一个类,然后在不命名它们的情况下创建该类的新实例 - 也许使用创建一堆实例的循环 - 我如何调用特定(或非特定)实例?例如,如果我正在生成一堆正方形,但我想将一个特定的移动到某个地方,我该怎么做?

对不起,如果这是一个完全的菜鸟问题,或者我错过了一些术语,但我对编程很陌生。

示例代码:

function example(x){
    this.x = x;
}

for(var i=0; i<10; i++){
    new example(1);
}
//now how would I get a specific instance of examples to have x = say, 10.
4

1 回答 1

4

您可以将每个正方形放在一个数组中并以这种方式访问​​它们:

function Square(i){
    this.index = i;
}
Square.prototype = {
    constructor: Square,
    intro: function(){
        console.log("I'm square number "+this.index);   
    }
}

var squares = [];

for(var i = 0;i < 10;i++){
    squares.push(new Square(i));
}

squares.forEach(function(square){
    // do something with each square
    square.intro();
});

演示:http: //jsfiddle.net/louisbros/MpcrT/1/

于 2013-03-10T01:28:33.470 回答