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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With