2014-10-26 64 views
1
var util = require('util'); 

function Entity(){ 
    //this.x == 10 at this point 
    this.x = 0; 
    this.y = 0; 
    this.globalInit(); 
} 

Entity.prototyp.globalInit = function(){ 
    console.log("this.x ", x); 
}; 

function Actor(){ 
    this.x = 10; 
    this.y = 10; 
    Actor.super_.apply(this, arguments); 
} 

util.inherits(Entity, Actor); 
var a = new Actor(); 
//outputs -> this.x 0 

我有這兩個構造函數。我想要在子構造函數中定義的屬性是最終的屬性。我可以將Actor.super_.apply移動到構造函數的頂部,但有一個初始化邏輯(globalInit),我想保留在父構造函數的末尾node.js繼承優先子構造函數屬性

回答

1

我可以看到兩個很好的解決方案。首先,父構造函數可以接受xy的參數,並將它們默認爲父類的值。

function Entity(x, y){ 
    this.x = typeof x === 'undefined' ? 0 : x; 
    this.y = typeof y === 'undefined' ? 0 : y; 
    this.globalInit(); 
} 

function Actor(){ 
    Actor.super_.call(this, 10, 10); 
} 

這種方法將工作最好的,如果有不是很多特性,它不是一個問題,讓他們在傳遞。它打破了幾分,如果初始化是非常複雜的。

第二種方法在初始化非常複雜的情況下更具普遍性。本質上,您想要引入工廠方法來生成對象的實例,然後可以執行任意複雜的初始化。例如,

function Entity(){} 
function Actor(){} 

function createEntity(){ 
    var e = new Entity(); 
    e.x = 0; 
    e.y = 0; 
    e.globalInit(); 
    return e; 
} 

function createActor(){ 
    var a = new Actor(); 
    a.x = 10; 
    a.y = 10; 
    a.globalInit(); 
    return a; 
} 

很明顯,這可以重構,以進一步幹代碼,可能與第一個解決方案的一些變體。

使用工廠方法而不是直接調用構造函數也會以其他方式增加值。它在一定程度上分離了兩個模塊,因此這些EntitiesActors的消費者不需要知道如何正確構建它們。它也允許你有多個不同的「構造函數」簽名而不需要痛苦的論證分析。