[英]Call child method class in parent with parent instance
我不希望我的父類太長,所以我從中分離一些方法並創建子類。
但是我不想將子類用作實例,但希望僅由父類使用。
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不是函數
我不希望我的父類太長,所以我從中分離了一些方法
好。
因此,我創建了子類,但是我不想將子類用作實例。
不,在這里子類化是錯誤的方法。 特別是如果您不想實例化子類,它甚至不是解決問題的方法。
要分離代碼單元,請將它們分解為單獨的函數。 那些不需要通過繼承鏈接到調用者,也完全不需要是類的方法。 寫吧
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();
如果要在子類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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.