node.jsinheritance喜欢子构造函数属性

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 ),我想保留在父构造函数的末尾

我可以看到两个很好的解决scheme。 首先,父构造函数可以接受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(); ex = 0; ey = 0; e.globalInit(); return e; } function createActor(){ var a = new Actor(); ax = 10; ay = 10; a.globalInit(); return a; } 

显然这可以被重构,以进一步干扰代码,可能与第一个解决scheme的一些变体。

使用工厂方法而不是直接调用构造函数也会以其他方式增加值。 它将这两个模块分开一些,这样这些EntitiesActors的消费者就不需要知道如何正确地构build它们。 它也允许你有多个不同的“构造函数”签名,而不需要痛苦的论证分析。