<分区>
我在使用 JavaScript(ES6) 时遇到了以下问题
class A{
constructor(){
this.foo();
}
foo(){
console.log("foo in A is called");
}
}
class B extends A{
constructor(){
super();
this.foo();
}
foo(){
console.log("foo in B is called");
}
}
我期望的是
foo in A is called
foo in B is called
但实际上是
foo in B is called
foo in B is called
我知道我可以通过简单地在类 B 的 foo 函数中添加 super.foo()
来解决这个问题
class B extends A{
constructor(){
super();
this.foo();
}
foo(){
super.foo() // add this line
console.log("foo in B is called");
}
}
但想象一个类似这样的场景:
子级必须覆盖父级的功能才能做一些额外的工作并防止外部访问原始功能。
class B extends A{
constructor(){
super();
this.initBar();
}
foo(){
super.foo();
this.bar.run(); //undefined
console.log("foo in B is called");
}
initBar(){
this.bar.run = function(){
console.log("bar is running");
};
}
}
在父级A
中构造时,this
似乎仍然指向子级B
。这就是为什么我无法访问父 A
的 foo
的原因。
如何让 this
调用在构造函数链中被子版本覆盖的父版本函数?
或者遇到这种情况有什么更好的解决方案吗?
编辑
所以,看完答案后,主要问题就变成了——
是否不鼓励将 initialize helpers
或 setter functions
放在 JavaScript 的构造函数中,因为 children 有机会覆盖它们?
为了更清楚地说明情况:(对我之前的坏例子感到抱歉 :( )
class A{
constructor(name){
this.setName(name);
}
setName(name){
this._name = name;
}
}
class B extends A{
constructor(name){
super(name);
this._div = document.createElementById("div");
}
setName(name){
super.setName(name);
this._div.appendChild(document.createTextNode(name));
}
}
new B("foo")
this._div
将是 undefined
。
这是不是一个坏主意,因为 child 将能够覆盖该函数?
class A{
constructor(name){
this.setName(name); // Is it bad?
}
...
}
所以我不应该像 Java、C++...那样在构造函数中使用initialize helpers
或 setter 函数
?
我必须手动调用像这样的 new A().init()
来帮助我初始化东西吗?