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

汤玛士

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

我基本上是试图构建一个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++) {

}

大家能给我的任何帮助将不胜感激。

谢谢,

汤姆

它的ikem

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

// 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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章