我想要赋值给我的原型DOM元素,这些元素也是在原型上用函数创建的。
我已经在下面的评论中描述了所有这些。
摘要:我的prototype函数应该生成DOM元素,将它们放入body中,并立即将对它们的引用分配给prototype的属性,例如。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.感谢您的帮助:)
发布于 2017-08-31 23:00:27
事实上,一旦它完成了它的工作,它根本不需要停留,所以我只需要内联它(也将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);
})();我确信您已经意识到了这一点,但我要强调的是:您将拥有one you数组,该数组由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);https://stackoverflow.com/questions/45984418
复制相似问题