【发布时间】:2018-02-09 14:02:20
【问题描述】:
我想将使用原型上的函数创建的 DOM 元素分配给我的原型。
我已经在下面的 cmets 中描述了所有内容。
总结:我的原型函数应该生成 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.
感谢您的帮助:)
【问题讨论】:
-
您确定要将对象分配给 instance 的属性,而不是全局/静态原型吗?为什么要共享 DOM 元素?通常这正是我们想要避免的。
标签: javascript oop object inheritance dom