![](/img/trans.png)
[英]Why can't we access Super Class Properties without calling Super Constructor in the Subclass?
[英]get subclass constructor in super class
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 ?
好吧,我不明白目标是什么,而是回答您的问题:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.