将元素从DOM分配给构造函数原型

时间:2017-08-31 14:52:49

标签: javascript oop object inheritance dom

我想分配我的原型DOM元素,这些元素也是在原型上用函数创建的。

我已经在下面的评论中描述了所有内容。

总结:我的原型函数应生成DOM元素,将它们放入body中并立即将它们引用到原型的属性,例如。 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.

感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

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等。)。

如果class对于每个Game都不同,那么在原型上使用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);