ome*_*ega -1 javascript ecmascript-6
如果我有类似的东西
class A {
constructor() {
this.test = function(){return 1;};
}
}
class B extends A {
constructor() {
super();
this.test = function(){alert( super.test() );};
}
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,但有没有办法可以访问父函数test()?
这不起作用,但有没有办法可以访问父函数test()?
因为您没有将原型用于基类方法,所以不能用super.test()它来引用它.相反,this.test它只是您当前对象的属性.如果有一些原因你不想将原型用于方法,你可以这样做:
class A {
constructor() {
this.test = function(){return 1;};
}
}
class B extends A {
constructor() {
super();
let priorTest = this.test;
this.test = function(){alert( priorTest.call(this) );};
}
}
Run Code Online (Sandbox Code Playgroud)
为了进一步说明,只有一个this.test属性,所以当你this.test = ...在B类中分配时,你会覆盖前一个,this.test所以你不能在实现中引用它.但是,您可以在覆盖它之前保存其值,然后使用它.
此外,有些人错误地认为this引用基类方法中的不同对象而不是派生类方法.事实并非如此.只有一个对象,基类和派生类都有该对象的方法.因此,this.test = xxx在基类中引用this.test = yyy与派生类完全相同的属性.原型上定义的方法实际上保存在单独的对象上,因此它们都可以独立存在.当您引用this.test并且当前对象上没有"own"属性时,Javascript将搜索原型链以查看它是否在原型链中找到具有所需名称的属性.如果是,那么它将返回/执行那个.
ES6的方法是使用ES6语法定义将使用原型的方法然后你可以super.test()用来引用基类实现,因为在原型链中每个类都有自己的对象,在其上定义方法搜索是否没有具有指定名称的"own"属性.
class A {
constructor() {
}
test() {
return 1;
}
}
class B extends A {
constructor() {
super();
}
test() {
alert(super.test());
}
}
Run Code Online (Sandbox Code Playgroud)