继承构造逻辑,但在Sub对象创建上运行Super构造函数

时间:2014-11-20 21:54:44

标签: javascript inheritance

我在其他语言中编写了继承类的东西,并且在创建子类时创建了对象的超类构造函数。但是,在我从javascript继承的模式中,超级构造函数实际上是在建立继承时运行的。

示例:

var thingy = function(){ this.constructionTime = new Date() };
var thing2 = function(){ this.type="thing2" };
thing2.prototype = new thingy();//thingy constructor actually runs here
var t2 = new thing2();//does NOT call thingy constructor
setTimeout(function(){
  var t3 = new thing2();
  t3.constructionTime == t2.constructionTime; // TRUE
},100);

然后我找到了一些不那么常见的例子,他们做了类似的事情:

var athing = function(){
    this.constructionDate = new Date();
}
athing.prototype.showDate = function(){ console.log(this.constructionDate) };

var something = function(){
    athing.apply(this);
    this.note = "I'm something";
}
var x = new something();

然后调用x = new something()会运行构造函数,但不会继承方法。所以我添加

something.prototype = athing.prototype;

不给x方法,但是新对象

y = new something();
y.showDate();//shows the date generated during its construction

有他们。

所以这是我可能过于宽泛的问题:我错过了什么吗?除了希望你的超级构造函数只运行一次之外,是否有理由不使用这种模式?

2 个答案:

答案 0 :(得分:0)

如果需要子类化,请考虑使用

function Constructor() {
    SuperConstructor.apply(this);
    /* ... */
}
Constructor.prototype = Object.create(SuperConstructor.prototype);
Object.defineProperty(Constructor.prototype, 'constructor', {
    value: Constructor,
    configurable: true,
    writable: true
});
  • SuperConstructor内拨打Constructor会使Constructor个实例在SuperConstructor内设置属性。
  • Constructor.prototype设置为Object.create(SuperConstructor.prototype)会使Constructor个实例从SuperConstructor.prototype继承属性。
  • 由于Constructor.prototype已被替换,因此必须手动添加constructor属性。使用defineProperty以使其不可枚举。

答案 1 :(得分:-1)

Javascript是一种免费的语言。尝试将继承和超级构造函数等经典概念融入其中并不是一个好主意。