【问题标题】:How the parent class properties get initialised without using super inside the child class?如何在不使用子类中的 super 的情况下初始化父类属性?
【发布时间】:2021-05-19 06:03:25
【问题描述】:
class Book{
  constructor(title,year){
    this.title = title
    this.year = year
  }
  getDetails(){
    return `Book ${this.title} is written in ${this.year}`
  }
}
class Magazine extends Book{
  // constructor(title,year,month){
  //   super(title,year)
  //   this.month = month
  // }
  
  fullDetails(){
    console.log(this.getDetails());
  }
}
const newBook = new Magazine('xxx','2022')
newBook.fullDetails() //output : Book xxx is written in 2022

在上面的代码中,Book 是父类,Magazine 是从 Book 类扩展而来的子类。然后我通过传递标题和年份的值为子类创建了一个对象。我已经注释掉了子类(杂志)中的构造函数和超级方法,但仍然初始化了父类属性(标题,年份)的属性,我可以得到输出。任何人都可以在不调用子类中的 super 的情况下解释这是怎么可能的吗?提前致谢。

【问题讨论】:

    标签: javascript class prototypal-inheritance


    【解决方案1】:

    如果您没有在子类中定义构造函数,则会自动调用父构造函数。只有覆盖它才能控制其中发生的事情。

    试试下面的,你会看到母类的构造函数没有被调用。

    class Book{
      constructor(title,year){
        this.title = title
        this.year = year
      }
      getDetails(){
        return `Book ${this.title} is written in ${this.year}`
      }
    }
    class Magazine extends Book{
      constructor(title,year,month){
        // Do nothing
        console.log('constructor is overidden');
    
     }
      
      fullDetails(){
        console.log(this.getDetails());
      }
    }
    const newBook = new Magazine('xxx','2022')
    newBook.fullDetails()
    

    【讨论】:

    • 谢谢,letibelim。我还有一个疑问。 import classes from './User.module.css' import { Component } from 'react' class User extends Component { render() { return <li className={classes.user}>{this.props.name}</li>; } } 这里我们没有使用 super 将 props 值传递给父 React 组件类,但是我们可以在 render 方法中使用 this.props。那么上述同样的原则在这里也适用吗?
    • 再一次,User 的父级是一个组件。所以当 React 发挥它的魔力时,它会实例化一个 User 对象(调用它的构造函数),在本例中是 Component 构造函数。 User 也继承了 Component 的所有属性,“props”就在其中。
    • 谢谢,Letibelim,现在我理解了这个概念。
    • 不客气。如果您觉得我的回答满意,请将其标记为已接受的答案!
    【解决方案2】:

    由于Magazine没有自己的构造函数,它继承了Book的构造函数,所以Book属性被初始化。

    如果子类有自己的构造函数,你只需要调用super(),因为它会覆盖父类的构造函数。

    【讨论】:

    • 谢谢,巴马尔。我还有一个疑问。 import classes from './User.module.css' import { Component } from 'react' class User extends Component { render() { return <li className={classes.user}>{this.props.name}</li>; } } 这里我们没有使用 super 将 props 值传递给父 React 组件类,但是我们可以在 render 方法中使用 this.props。那么同样的上述原则在这里也适用吗?
    • 同理。你还没有在User类中定义构造函数,所以使用Component构造函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2020-02-12
    相关资源
    最近更新 更多