问题描述
我不希望我的父类太长,所以我从中分离一些方法并创建子类。
但是我不想将子类用作实例,但希望仅由父类使用。
class Parent {
parentMethod() {
this.foo(); // execute from parent
}
}
class Child extends Parent {
foo() {
console.log('foo!');
}
}
const parent = new Parent();
parent.parentMethod(); // execute parent method which execute child method
原因:
未捕获的TypeError:this.foo不是函数
1楼
我不希望我的父类太长,所以我从中分离了一些方法
好。
因此,我创建了子类,但是我不想将子类用作实例。
不,在这里子类化是错误的方法。 特别是如果您不想实例化子类,它甚至不是解决问题的方法。
要分离代码单元,请将它们分解为单独的函数。 那些不需要通过继承链接到调用者,也完全不需要是类的方法。 写吧
class MyClass {
myMethod() {
foo();
}
}
function foo() {
console.log('foo!');
}
const instance = new MyClass();
instance.myMethod();
或由多个较小的助手组成您的对象:
class Outer {
constructor() {
this.helper = new Inner();
}
myMethod() {
this.helper.foo();
}
}
class Inner {
foo() {
console.log('foo!');
}
}
const instance = new Outer();
instance.myMethod();
2楼
如果要在子类Child
类中使用Parent
类,则需要执行以下操作:
class Parent {
foo() {
console.log('foo!');
}
}
class Child extends Parent {
constructor() {
super();
}
}
let c = new Child(); //instantiate Child class
c.foo(); // here you are calling super.foo(); which is the Parent classes method for foo.
//foo!
super关键字用于访问和调用对象父对象上的函数。
或者,或者,如果您希望在包装foo父方法的子类上创建一个方法,而不是通过在子构造函数中调用super
来实例化父类来访问它:
class Parent {
foo() {
console.log('foo!');
}
}
class Child extends Parent {
method() {
this.foo();
}
}
let c = new Child();
c.method();