Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why console.log(super) in React Component constructor throw an Error?

I want to console the super in my InheritComponent constructor method. But in chrome console, it throw an Error. Why?

class BaseComponent extends React.Component{

    static defaultProps = {
        title: 'Learn React By Examples'
    }

    constructor(props) {
        console.log(props);
        super(props);
    }

    setTitle(title) {
        document.title = title || this.props.title;
        return document.title;
    }
}

class InheritComponent extends BaseComponent{
  
    state = {
      title: ''
    };

    constructor(props) {
        super(props);
        
        //here throw an Error. Why? I want to console.log `super`
        console.log(super);
    }

    componentDidMount() {
        const title = this.setTitle('组件继承')
        this.setState({title});
    }

    render() {
        return <div>
            <p>I inherit BaseComponent</p>
            <p>current title is {this.state.title}</p>
            
        </div>
    }
}

ReactDOM.render(
  <InheritComponent />,
  document.body
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Above is my demo code.

like image 656
slideshowp2 Avatar asked Dec 25 '22 02:12

slideshowp2


2 Answers

Reason is simple: super is a keyword, not a function nor any variable. You cannot log super the same as you cannot log var or new keywords.

If you want to log the constructor of your parent, you can try:

console.log(super.constructor);

In fact, super() is just shorthand for super.constructor().

See more: https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Operators/super

like image 178
Karol Selak Avatar answered Dec 26 '22 16:12

Karol Selak


super is a keyword, you can't use it like a variable. The only allowed ways to use super are outlined in the MDN documentation for it:

super([arguments]); // calls the parent constructor.

super.functionOnParent([arguments]);

If you want to print the parent class, use console.log(super.constructor) instead.

like image 41
noppa Avatar answered Dec 26 '22 16:12

noppa