簡體   English   中英

將元素從DOM分配給構造函數原型

[英]Assigning elements from the DOM to the constructor prototype

我想分配給我的原型DOM元素,這些元素也是用原型上的函數創建的。

我已經在下面的評論中描述了所有內容。

簡介:我的原型函數應生成DOM元素,將其放入正文中,然后立即將對它們的引用分配給原型的屬性。 Game.prototype.boxes = //新創建的DOM元素。

function Game() {

    this.class = 'box';
    // this.boxes = this.createBoxes(); // It almost works, but isn't on prototype and is duplicated, when I create instance of Monstar class.

}

// Game.prototype.boxes = this.createBoxes(); // I know, in this context 'this' isn't my constructor, but this is method I want to achieve
// Game.prototype.boxes = $('.' + this.class); // As above - 'this' isn't my constructor
Game.prototype.boxes = Game.prototype.createBoxes(); // Alternative test from the lines above. It have to be on my prototype.

Game.prototype.createBoxes = function () {

    var docFragment = document.createDocumentFragment();

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

        var elem = $('<div>', {
            class: this.class
        });

        elem.appendTo(docFragment);

    }

    $(docFragment).appendTo($('body'));

    return $('.' + this.class);

};

function Monster() {

    Game.call(this);

    console.log(this.boxes); // Finally this should returns array with my DOM elements created using prototype createBoxes function.

}

Monster.prototype = Object.create(Game.prototype);
Monster.prototype.constructor = Monster;

var game = new Game(),
    monster = new Monster();

console.log(game.boxes); // Finally this should returns array with my DOM elements created using prototype createBoxes function.

謝謝你的幫助 :)

無需將createBoxes包含在原型中。 實際上,它在完成工作后根本不需要堅持下去,因此我只需要對其進行內聯(將class屬性也從實例移至函數):

Game.class = "box";
Game.prototype.boxes = (function() {
    var docFragment = document.createDocumentFragment();
    for(var i  = 0; i < 20; i++) {
        var elem = $('<div>', {
            class: this.class
        });
        elem.appendTo(docFragment);
    }
    $(docFragment).appendTo($('body'));
    return $('.' + Game.class);
})();

我敢肯定,您會意識到這一點,但要強調一點:您將擁有組盒子,所有Game實例(以及Monster所有實例等)都將共享這些盒子。

如果每個Game class都不同,那么在原型上boxes根本沒有任何意義。


這是該更改的完整代碼:

function Game() {
}
Game.class = "box";
Game.prototype.boxes = (function() {
    var docFragment = document.createDocumentFragment();
    for(var i  = 0; i < 20; i++) {
        var elem = $('<div>', {
            class: this.class
        });
        elem.appendTo(docFragment);
    }
    $(docFragment).appendTo($('body'));
    return $('.' + Game.class);
})();

function Monster() {
    Game.call(this);
    console.log(this.boxes);
}
Monster.prototype = Object.create(Game.prototype);
Monster.prototype.constructor = Monster;

var game = new Game(),
    monster = new Monster();

console.log(game.boxes);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM