[英]js call base class constructor
Is it possible to call a baseclass constructor from a class? 是否可以从类中调用基类构造函数?
class BaseCls {
}
class Cls extend BaseCls {
constructor(options){
super(options)
}
}
var instance = new Cls();
Now I want an instance of the baseclas. 现在我想要一个Baseclas的实例。 Something like this:
像这样:
var baseInstance = new Cls.parent()
I know that I could just call new BaseCls(), but doing it the other way allows me to have only one import. 我知道我可以只调用新的BaseCls(),但是以另一种方式进行操作则只能导入一个。
The superclass is the prototype of the subclass* (which is why superclass static
methods are accessible on the subclass), so Object.getPrototypeOf
will give you the superclass: 超类是子类*的原型(这就是为什么可以在子类上访问超类
static
方法的原因),因此Object.getPrototypeOf
将为您提供超类:
class BaseCls { constructor() { console.log("BaseCls"); } } class Cls extends BaseCls { constructor(options){ super(options) console.log("Cls"); } } var base = Object.getPrototypeOf(Cls); var instance = new base();
You don't have to separate the statements, but if you want to combine them, you have to put ()
around the call to Object.getPrototypeOf
(otherwise new
tries to consume it): 您不必到报表分开,但如果你希望将它们组合,你必须把
()
调用周围Object.getPrototypeOf
(否则new
尝试使用它):
var instance = new (Object.getPrototypeOf(Cls))();
And of course, if you wanted to do this generically from a reference to an instance of Cls
, it would be: 当然,如果您想从对
Cls
实例的引用中进行一般性的设置,那就是:
var superInstance = new (Object.getPrototypeOf(instance.constructor))();
...provided instance
doesn't have an own constructor
property. ...提供的
instance
没有自己的constructor
属性。 Or the rather more convoluted: 或更复杂的是:
var superInstance = new (Object.getPrototypeOf(Object.getPrototypeOf(instance).constructor))();
...if it may have its own constructor
property. ...如果它可能有自己的
constructor
属性。
* Yes, really. * 对真的。 When you use
B extends A
, there are two parallel lines of inheritance set up: A.prototype
is made the prototype of B.prototype
, and A
is made the prototype of B
(whereas in ES5 and earlier, the prototype of a function was always Function.prototype
). 当使用
B extends A
,有继承的两条平行线设置: A.prototype
由原型B.prototype
, 和 A
制成的原型B
(而在ES5和更早,一个函数的原型是始终为Function.prototype
)。
Given: 鉴于:
class A {
}
class B extends A {
}
the inheritance looks like this: 继承看起来像这样:
B −−−−−−−−−−−−−−> A −−−−−−−−−−−−−−> Function.prototype B.prototype −−−−> A.prototype −−−−> Object.prototype
class A { } class B extends A { } console.log(Object.getPrototypeOf(B) === A); console.log(Object.getPrototypeOf(A) === Function.prototype); console.log(Object.getPrototypeOf(B.prototype) === A.prototype); console.log(Object.getPrototypeOf(A.prototype) === Object.prototype);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.