我想分配到与功能也对原型创建我的原型的DOM元素分配元素。从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.
感谢所有帮助:)
当然你要的对象分配给你的*实例*的属性,而不是全局/静态的原型?你为什么要共享DOM元素?通常这正是我们想要避免的。 – Bergi