Javascript 将其绑定到es6类构造函数
我试图将Javascript 将其绑定到es6类构造函数,javascript,Javascript,我试图将这个应用到es6类的构造函数中,以获得类似这样的“构造函数合并”: class D { constructor(name){ this.name=name this.methodD=function(){} } } class C extends D { constructor(name,name2){ super(name) this.name2=name2 } } function C
这个应用到es6类的构造函数中,以获得类似这样的“构造函数合并”:
class D {
constructor(name){
this.name=name
this.methodD=function(){}
}
}
class C extends D {
constructor(name,name2){
super(name)
this.name2=name2
}
}
function Custom(name,name2){
if (this instanceof Custom){
Function.prototype.bind.call(C.prototype.constructor,this,...arguments)
}
}
Custom.prototype.method=function(){}
const cc=new Custom('name','name2')
我希望使用与C
相同的构造函数来构造cc
,因此得到cc.name='name';cc.methodD()代码>
提前感谢您的帮助。您可以尝试在Custom
的内部创建C
的新实例,并使用es6Object.setPrototypeOf()重新定义原型
请注意,在这种情况下,Custom
只返回像C
一样构造的对象,其原型不包含C.prototype
和D.prototype
的方法,只包含它们自己的方法,比如D
类的methodD
还要注意的是,根据文章,这种方法可能会影响浏览器的性能
D类{
建造师(姓名){
this.name=name
this.methodD=function(){}
}
}
C类扩展到D类{
构造函数(名称,名称2){
超级(姓名)
this.name2=name2
}
}
自定义函数(名称、名称2){
设cls=新的C(…参数);
setPrototypeOf(cls,Custom.prototype);
返回cls;
}
Custom.prototype.method=function(){}
const cc=new Custom('name','name2')
console.log(cc.name)
console.log(cc.name2)
console.log(cc.methodD)
console.log(cc instanceof Custom)
您可以尝试在Custom
的内部创建C
的新实例,并使用es6Object.setPrototypeOf()重新定义原型
请注意,在这种情况下,Custom
只返回像C
一样构造的对象,其原型不包含C.prototype
和D.prototype
的方法,只包含它们自己的方法,比如D
类的methodD
还要注意的是,根据文章,这种方法可能会影响浏览器的性能
D类{
建造师(姓名){
this.name=name
this.methodD=function(){}
}
}
C类扩展到D类{
构造函数(名称,名称2){
超级(姓名)
this.name2=name2
}
}
自定义函数(名称、名称2){
设cls=新的C(…参数);
setPrototypeOf(cls,Custom.prototype);
返回cls;
}
Custom.prototype.method=function(){}
const cc=new Custom('name','name2')
console.log(cc.name)
console.log(cc.name2)
console.log(cc.methodD)
console.log(cc instanceof Custom)