在超类中获取子类构造函数

时间:2014-05-14 17:35:15

标签: javascript

var Super = function() {}
Super.prototype.newOfThisKind = function() {
    return new this.myConstructor()
}
var Sub1 = function() { this.myConstructor = Sub1 }
var Sub2 = function() { this.myConstructor = Sub2 }
Sub1.prototype = new Super()
Sub2.prototype = new Super()
console.assert(new Sub1().newOfThisKind() instanceof Sub1)
console.assert(new Sub2().newOfThisKind() instanceof Sub2)

此代码按预期工作,但如何在不在每个子类中设置 myConstructor 的情况下编写 newOfThisKind

1 个答案:

答案 0 :(得分:1)

嗯,我不明白目标是什么,但回答你的问题:

    var Super = function () { }
    Super.prototype.newOfThisKind = function () {
        return Object.create(this);
    }
    var Sub1 = function () { }
    var Sub2 = function () { }
    Sub1.prototype = new Super()
    Sub2.prototype = new Super()
    console.assert(new Sub1().newOfThisKind() instanceof Sub1)
    console.assert(new Sub2().newOfThisKind() instanceof Sub2)