Javascript super() 在没有任何参数的情况下做什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39822941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:56:09  来源:igfitidea点击:

what does super() do without any arguments?

javascriptreactjsecmascript-6super

提问by mangocaptain

I'm learning react from the docs, but not sure what the super()does in this example. Usually, doesn't it take the arguments that are passed to making a new instance and then calls React.Component's constructor method to incorporate these arguments into the instance? What does it do without any arguments?

我正在从docs学习 react ,但不确定super()这个例子中的作用。通常情况下,不是将传入的参数用于创建新实例,然后调用 React.Component 的构造函数方法将这些参数合并到实例中吗?没有任何参数它会做什么?

class LikeButton extends React.Component {
  constructor() {
    super();
    this.state = {
      liked: false
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({liked: !this.state.liked});
  }
  render() {
    const text = this.state.liked ? 'liked' : 'haven\'t liked';
    return (
      <div onClick={this.handleClick}>
        You {text} this. Click to toggle.
      </div>
    );
  }
}

ReactDOM.render(
  <LikeButton />,
  document.getElementById('example')
);

回答by Varun Munjeti

In ES6, derived classes have to call super()if they have a constructor. In react, all components extend from the Component class.

在 ES6 中,派生类super()如果有构造函数就必须调用。在 React 中,所有组件都从 Component 类扩展而来。

You don't actually need a constructor for every ES6/react class. If no custom constructor is defined, it will use the default constructor. For base classes, it is:

你实际上并不需要每个 ES6/react 类的构造函数。如果未定义自定义构造函数,它将使用默认构造函数。对于基类,它是:

constructor() {}

And for derived classes, the default constructor is:

对于派生类,默认构造函数是:

constructor(...args) {
  super(...args);
}

You also need to call super()before accessing this, since thisis not initialized until super()is called.

您还需要super()在访问之前调用this,因为在调用之前this不会初始化super()

There are a few reasons to use a custom constructor in react. One is that you can set the initial state within the constructor using this.state = ...instead of using the getInitialStatelifecycle method.

在 React 中使用自定义构造函数有几个原因。一种是您可以使用this.state = ...而不是使用getInitialState生命周期方法在构造函数中设置初始状态。

You can also bind class methods inside the constructor with this.someClassMethod = this.someClassMethod.bind(this). It's actually better to bind methods in the constructor since they will only be created once. Otherwise if you call bindor use arrow functions to bind methods anywhere outside the constructor (like in the rendermethod), it will actually end up creating a new instance of the function on every render. Read more about that here.

您还可以使用this.someClassMethod = this.someClassMethod.bind(this). 在构造函数中绑定方法实际上更好,因为它们只会被创建一次。否则,如果您调用bind或使用箭头函数在构造函数之外的任何位置绑定方法(如在render方法中),它实际上最终会在每次渲染时创建函数的新实例。在此处阅读更多相关信息。

If you want to use this.propsin the constructor, you need to call superwith props as an argument:

如果要this.props在构造函数中使用,则需要以superprops 为参数调用:

constructor(props) {
  super(props);
  this.state = {count: props.initialCount};
}

If you don't, then this.propsis undefined in the constructor. However, you can still access this.propsanywhere else in the class outside the constructor without needing to do anything with it in the constructor.

如果不这样做,则this.props在构造函数中未定义。但是,您仍然可以this.props在构造函数之外访问类中的任何其他位置,而无需在构造函数中对其进行任何操作。

回答by Willem van der Veen

The superkeyword in JavaScript is used in order to call the methods of the parent class. By itself, super()is used within a constructor function to call the parent constructor function. For example:

superJavaScript 中的关键字用于调用父类的方法。super()在构造函数中使用它本身来调用父构造函数。例如:

class Animal {
  
  constructor(age) {
    console.log('Animal being made');
    this.age = age;
  }
  
  returnAge() {
    return this.age;
  }
  
}

class Dog extends Animal {

  constructor (age){
    super(age);
  }
  
  logAgeDog () {
    console.log(`This dog is: ${ super.returnAge()} years old`);
  }
  
}

const dog = new Dog(5);


console.log(dog);

dog.logAgeDog();

In this example we have a Dog class which extendsan Animal class. The Dog class uses the superkeyword twice. The first occurence is in the constructor, when super()is used in the constructor it will call the parent class constructor. Therefore we have to give the age property as an argument to it. Now the Dog successfully has an age property.

在这个例子中,我们有一个 Dog 类,它extends是一个 Animal 类。Dog 类使用super关键字两次。第一次出现在构造函数中,当super()在构造函数中使用时,它会调用父类的构造函数。因此,我们必须将 age 属性作为参数。现在 Dog 成功地拥有了 age 属性。

We can also use superoutside of the constructor in order to access the parent's 'class' (i.e. prototype) properties and methods. We use this in the logAgeDogfunction located in the Dog class. We use the following code:

我们还可以super在构造函数之外使用以访问父类的“类”(即原型)属性和方法。我们在logAgeDog位于 Dog 类的函数中使用它。我们使用以下代码:

super.returnAge();

You should read this as:

你应该把它读成:

Animal.returnAge();     // superClass.returnAge()

Why do I need this in React?

为什么我在 React 中需要这个?

You need the super()keyword in React onlywhen implementing a constructor. You have to do the following:

只有在实现构造函数时super()需要React 中的关键字。您必须执行以下操作:

constructor(props) {
  super(props);
  // Don't call this.setState() here!
}

the parent class which is named Componentneeds to do some initialization on its own in order for React to work fine. If you implement a constructor without a super(props)call this.propsin Componentwill be undefinedwhich can lead to bugs.

被命名的父类Component需要自己做一些初始化才能让 React 正常工作。如果您在没有super(props)调用的情况下实现构造函数this.propsComponent将会undefined导致错误。