ES6的super关键字如何调用父类方法

es6中super关键字与父类构造函数调用的关系在于,它强制在子类构造函数中调用父类构造函数以完成初始化。1. 在子类构造函数中必须先调用super()才能使用this,确保父类初始化完成;2. super()会绑定this到子类实例,使其后续可安全访问和扩展属性;3. 除了构造函数,super也可用于子类普通方法中调用父类方法,此时this仍指向子类实例;4. 在静态方法中,super用于调用父类静态方法,且this指向当前子类而非父类。

ES6的super关键字如何调用父类方法

ES6的super关键字,在我看来,它最核心的功能就是提供了一个清晰、直观的机制,让我们在子类中能够方便地访问和调用父类的方法,包括构造函数和普通方法。这大大简化了类继承中的代码复用,避免了直接操作原型链的复杂性。

ES6的super关键字如何调用父类方法

解决方案

要使用ES6的super关键字调用父类方法,主要有两种场景:在子类的构造函数中调用父类构造函数,以及在子类的普通方法中调用父类的同名或不同名方法。

1. 在子类构造函数中调用父类构造函数: 这是最常见也最强制的用法。在子类的constructor中,你必须在访问this之前调用super()。这确保了父类部分的初始化得以完成。

ES6的super关键字如何调用父类方法

class Animal {   constructor(name) {     this.name = name;     console.log(`Animal ${this.name} created.`);   }   speak() {     return `${this.name} makes a sound.`;   } }  class Dog extends Animal {   constructor(name, breed) {     super(name); // 调用父类Animal的constructor,传入name参数     this.breed = breed;     console.log(`Dog ${this.name} of breed ${this.breed} created.`);   }   speak() {     const parentSound = super.speak(); // 调用父类Animal的speak方法     return `${parentSound} Woof! I'm a ${this.breed}.`;   } }  const myDog = new Dog('Buddy', 'Golden Retriever'); // 输出: // Animal Buddy created. // Dog Buddy of breed Golden Retriever created. console.log(myDog.speak()); // 输出: Buddy makes a sound. Woof! I'm a Golden Retriever.

2. 在子类普通方法中调用父类方法: 在子类的实例方法中,你可以使用super.methodName()来调用父类中定义的方法。这里的this上下文会保持为子类的实例。

class Parent {   greet() {     return `Hello from Parent.`;   }   showThis() {     return `Parent's this is: ${this.constructor.name}`;   } }  class Child extends Parent {   greet() {     // 调用父类的greet方法,并在此基础上添加内容     return `${super.greet()} Hello from Child.`;   }   showChildThis() {     // 即使调用父类方法,父类方法内部的this仍然指向Child实例     return `Child calling parent's showThis: ${super.showThis()}`;   } }  const childInstance = new Child(); console.log(childInstance.greet()); // 输出: Hello from Parent. Hello from Child. console.log(childInstance.showChildThis()); // 输出: Child calling parent's showThis: Parent's this is: Child

ES6中super关键字与父类构造函数调用有什么关系?

在ES6的类继承体系中,super关键字在子类构造函数中的作用是至关重要的,它直接扮演了调用父类构造函数的角色。这其实是 JavaScript 语言设计上一个挺有意思的约束。我个人觉得,它强制你先完成父类的初始化,再进行子类的个性化定制,这逻辑上很顺畅,也避免了许多潜在的 this 引用问题。就像盖房子,你得先打好地基,才能往上加层和装修,对吧?

ES6的super关键字如何调用父类方法

具体来说:

  1. 强制性调用: 如果一个类继承自另一个类(即使用了extends关键字),并且它定义了自己的constructor,那么在这个子类的constructor内部,你必须调用super()。如果没有调用,或者在调用super()之前尝试使用this关键字,JavaScript会抛出引用错误(ReferenceError)。
  2. 初始化父类: super()的调用会执行父类的构造函数,从而初始化父类中定义的属性和方法。这确保了子类实例拥有父类所需的所有基本特性。
  3. 绑定this: super()的调用还会负责绑定this。在子类构造函数中,this在super()调用之前是不可用的。一旦super()被调用,this就会被正确地初始化并指向子类的实例,你就可以安全地使用this来定义子类特有的属性了。
class BaseComponent {   constructor(props) {     this.props = props;     console.log('BaseComponent initialized with props:', this.props);   } }  class CustomButton extends BaseComponent {   constructor(props, label) {     // 在这里使用this会报错,因为super()尚未被调用     // console.log(this); // ReferenceError     super(props); // 必须先调用父类构造函数     this.label = label; // 现在可以安全地使用this了     console.log('CustomButton initialized with label:', this.label);   }    render() {     return `<button>${this.label} - ${this.props.theme}</button>`;   } }  const myButton = new CustomButton({ theme: 'dark' }, 'Click Me'); // 输出: // BaseComponent initialized with props: { theme: 'dark' } // CustomButton initialized with label: Click Me console.log(myButton.render()); // <button>Click Me - dark</button>

除了构造函数,super在普通方法中如何调用父类方法?

在子类的普通方法(非静态方法)中,super关键字允许你调用父类中定义的同名或不同名方法。这里有个小陷阱,或者说一个需要特别注意的地方:当你在子类方法里通过 super.methodName() 调用父类方法时,父类方法内部的 this 依然指向的是子类的实例。这很关键,因为它意味着父类方法会作用于子类的属性,而不是父类自身的属性。我第一次遇到这个的时候,也愣了一下,觉得有点反直觉,但仔细想想,这正是多态性的一种体现,非常合理。

调用方式: super.methodName(args)

关键点:

  1. this的指向: 当你通过super.methodName()调用父类方法时,该父类方法内部的this上下文会自动绑定到当前的子类实例。这意味着,如果父类方法中使用了this来访问属性或调用其他方法,它实际上是在操作子类实例的属性和方法。
  2. 方法覆盖与扩展: 这种机制非常适合实现方法覆盖(override)和方法扩展(extension)。你可以在子类中重写父类的方法,但同时又能在重写的方法内部调用父类的原始实现,从而在保留父类功能的基础上增加子类特有的逻辑。
class Product {   constructor(name, price) {     this.name = name;     this.price = price;   }   getDescription() {     return `${this.name} costs $${this.price}.`;   }   // 父类方法中使用this   getFormattedPrice() {     return `$${this.price.toFixed(2)}`;   } }  class DiscountedProduct extends Product {   constructor(name, price, discount) {     super(name, price);     this.discount = discount;   }   getDescription() {     // 调用父类的getDescription方法,并在此基础上添加折扣信息     const baseDescription = super.getDescription();     const discountedPrice = this.price * (1 - this.discount); // 使用子类实例的price     return `${baseDescription} With a ${this.discount * 100}% discount, it's now $${discountedPrice.toFixed(2)}.`;   }   // 演示父类方法中this指向子类实例   getDiscountedFormattedPrice() {     // super.getFormattedPrice() 内部的 this 依然指向 DiscountedProduct 实例     return `Original: ${super.getFormattedPrice()}, Discounted: $${(this.price * (1 - this.discount)).toFixed(2)}`;   } }  const laptop = new DiscountedProduct('Laptop', 1200, 0.15); console.log(laptop.getDescription()); // 输出: Laptop costs $1200. With a 15% discount, it's now $1020.00. console.log(laptop.getDiscountedFormattedPrice()); // 输出: Original: $1200.00, Discounted: $1020.00 (父类方法中的this.price实际上是子类实例的price)

在静态方法中,super关键字如何调用父类的静态方法?

静态方法中的 super 行为和实例方法中的 super 有些异曲同工之妙,但又有所不同。它同样提供了一个通向父类静态方法的通道。我常觉得,这就像是家族企业里,老一辈的经营理念或决策模式,可以直接被新一代继承和引用,而不需要通过某个具体的‘产品’(实例)来传递。这让类层面的工具函数或辅助方法变得非常灵活。

当你在一个子类的静态方法中,需要调用其父类的静态方法时,同样可以使用super关键字。

调用方式: super.staticMethodName(args)

关键点:

  1. 类级别的调用: 静态方法是属于类本身,而不是类的实例。因此,在静态方法中使用super调用父类静态方法,也是在类级别上进行的。
  2. this的指向: 在静态方法中,this指向的是当前类本身(即调用该静态方法的类)。当通过super.staticMethodName()调用父类静态方法时,父类静态方法内部的this也同样指向调用者(子类),而不是父类。这使得父类静态方法可以基于子类的信息进行操作。
class Calculator {   static add(a, b) {     return a + b;   }   static multiply(a, b) {     return a * b;   }   static getOperationName() {     return `${this.name} operations`; // 这里的this指向调用者   } }  class AdvancedCalculator extends Calculator {   static subtract(a, b) {     return a - b;   }   static performCalculations(x, y) {     // 调用父类的静态方法     const sum = super.add(x, y);     const product = super.multiply(x, y);     const sub = this.subtract(x, y); // 调用自身的静态方法     return `Sum: ${sum}, Product: ${product}, Subtraction: ${sub}`;   }   static getAdvancedOperationName() {     // 调用父类静态方法,父类方法中的this指向AdvancedCalculator     return `${super.getOperationName()} (Advanced)`;   } }  console.log(AdvancedCalculator.performCalculations(10, 5)); // 输出: Sum: 15, Product: 50, Subtraction: 5  console.log(AdvancedCalculator.getAdvancedOperationName()); // 输出: AdvancedCalculator operations (Advanced) // (因为super.getOperationName()内部的this指向AdvancedCalculator)

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享