在JavaScript中,"super" 是一個 keyword,他用於在子類別中,可以引用其父類別的屬性和方法。 以下兩種情況 : ### 1. 在子類別建構函式中,使用"super()",調用父類別的建構函式。 這樣可以繼承父類別的屬性和方法。 ```js! class Parent { constructor(name) { this.name = name; } } class Child extends Parent { constructor(name, age) { super(name); // 調用父類別的建構函式 this.age = age; } } const child = new Child('John', 10); console.log(child.name); // 'John' console.log(child.age); // 10 ``` ### 2. 在子類別方法中,使用"super()"來引用父類別的方法。 這樣可以在子類別中擴張/修改父類別的行為。 ```js! class Parent { sayHello() { console.log('Hello'); } } class Child extends Parent { sayHello() { super.sayHello(); // 調用父類別的方法 console.log('World'); } } const child = new Child(); child.sayHello(); // 'Hello','World' ``` ## 所以"super()"到底可以做什麼? 他是可以在子類別中引用父類別的 keyword,用於繼承/擴張父類別的屬性和方法。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up