使用JavaScript使用循环动态创建对象

时间:2013-11-16 22:29:33

标签: javascript oop loops dynamic

我希望有人能指出我正确的方向。

我基本上是在尝试构建一个OOP解决方案,根据类动态生成大量对象,然后通过类方法运行与每个对象关联的方法。

以下是我的非动态代码。

// Create videoObject class
function videoObject(videoTag, videoNum){
    this.videoTag = videoTag;
    this.videoNum = videoNum;
    this.videoTagHref = videoTag.attr("href");
    this.videoId = function(videoTag){
    };
    this.addAttrId = function(videoNum){
    };
    this.printObjectInfo = function(videoId){
    };
    this.embedVideo = function(videoId, videoTag, videoNum){
    };
    this.buildControls = function(videoTag){
    };
};

// Manually create two objects and run class methods
var newVideo1 = new videoObject($('.yt-player-0'), 0);
newVideo1.videoId();
newVideo1.addAttrId();
newVideo1.embedVideo();
newVideo1.buildControls();

var newVideo2 = new videoObject($('.yt-player-1'), 1);
newVideo2.videoId();
newVideo2.addAttrId();
newVideo2.embedVideo();
newVideo2.buildControls();

// I want to somehow create newVideo1 and newVideo2 dynamically inside a loop like below
var length = $('.yt-player').length;

for (var i = 0; i < length; i++) {

}

你们可以给我的任何帮助都会非常感激。

谢谢,

汤姆

2 个答案:

答案 0 :(得分:1)

我会尝试这个(未经测试):

// Create videoObject class
function videoObject(videoTag, videoNum){
    this.videoTag = videoTag;
    this.videoNum = videoNum;
    this.videoTagHref = videoTag.attr("href");
    this.videoId = function(videoTag){
    };
    this.addAttrId = function(videoNum){
    };
    this.printObjectInfo = function(videoId){
    };
    this.embedVideo = function(videoId, videoTag, videoNum){
    };
    this.buildControls = function(videoTag){
    };
    // call these methods in your constructor instead of repeatedly from elsewhere
    this.videoId();
    this.addAttrId();
    this.embedVideo();
    this.buildControls();
    // send back a reference to this newly created video object to the loop
    return this;
};

// create an array of video object references
var videoObjectReferences = [];
for (var i=0;i<10;i++){
    // building ten video objects here, with ids of: yt-player-0, yt-player-1, etc.
    // build a selector to reference them via id, not by class with a dot as you have in your question
    var sel = String("#yt-player-" + i);
    // create the object and store a reference to the video object so you can do something with it later
    var newVid = new videoObject($(sel), i);
    // build list of references
    videoObjectReferences.push(newVid);
}

答案 1 :(得分:0)

var videos = [2]; 
for(var i = 0; i < 2; i++){
   videos[i] = new videoObject($('.yt-player-0'), 0);
   /*Extra method calls here*/ 
}

如果您总是希望使用这些额外的方法调用来初始化对象,您可能需要考虑让对象构造函数为您处理。那么你的客户端代码会更清晰。