2017-08-31 66 views
0

我想分配到與功能也對原型創建我的原型的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. 

感謝所有幫助:)

+0

當然你要的對象分配給你的*實例*的屬性,而不是全局/靜態的原型?你爲什麼要共享DOM元素?通常這正是我們想要避免的。 – Bergi

回答

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); 
+1

您還可以內聯'this.class'常數'「盒子」' – Bergi