Search code examples
javascriptreact-nativeconstructorsuper

constructor() and super() methods in Javascript


I'm currently learning how to build iOS apps using React Native. I have some experience in Javascript and HTML (not a whole lot, I'm coming straight from years of Swift and Objective-C). I am working through an example code snippet about creating stateful components using (a) property initializer or (b) the constructor method. Here are my code snippets for both respectively.

I completely understand the property initializer way of doing it. I'm confused on how the constructor way of doing it works. My question is:

  1. What do the constructor and super methods do? I understand that these are not part of React Native, rather of Javascript itself.

  2. Would there be a reason you would pick the property initializer way over the constructor method or vice versa?

Thanks! Mohammad

// Property Initiliazer Way of Doing It
class PropertyInitializerStatefulComponent extends React.Component {

    // 1. State is initialized when a component is created as demonstrated below
    // 2. Once initialized, it is avalable as a this.state.
    state = {

        year: 2019,
        name: 'Johnny Appleseed',
        colors: ['blue']

    }

    render() {

        // Implementation of Point 2
        return(
            <View>
                <Text>My name is  {this.state.name}</Text>
                <Text>The year is: {this.state.year}</Text>
                <Text>My favorite colors are: {this.state.colors[0]}</Text>
            </View>
        )
    }
}

// Making a stateful component using the constructor method...

class ConstructorStatefulComponent extends React.Component {

    // ??
    constructor() {

        // ??
        super() 
        this.state = {

            year: 2019,
            name: 'Johnny Appleseed',
            colors: ['blue']

        }
    }

    render() {

        // Implementation of Point 2
        return(
            <View>
                <Text>My name is  {this.state.name}</Text>
                <Text>The year is: {this.state.year}</Text>
                <Text>My favorite colors are: {this.state.colors[0]}</Text>
            </View>
        )
    }

}


Solution

  • super() is used to call the parent's function.

    In your code, you wrote super() in the constructor so it runs the constructor() of React.Component.

    You can use super() not only in the constructor but also in the other functions.

    For example, the parent class(React.Component in your code) has a method func1() and it was defined like the following code.

    function func1() {
      this.a = 0;
      this.b = 0;
    }
    

    But you need to set another property c in the func1() of the child class. In that case you should redefine the func1 in the child class and it should be the following.

    function func1() {
      super.func1(); // it will set a and b as 0
      this.c = 0;
    }