问题
Using ES6+ syntax in React/React-Native, the variable foo
, when defined outside of the constructor is somehow transformed into an instance variable when called with this.
. Is my assertion true? Why does it even work, when not instantiated in the constructor? Here a corresponding React Native code snippet:
class myComponent extends Component {
constructor() {
super();
}
foo = "bar";
render() {
return ( <View>{ this.foo }</View> );
}
}
This discussion about ES7 property initializers shows how the state
variable is prominently used in this way in React/React Native.
So far related Stack Overflow discussions I read through here and here could not answer this question for me..
回答1:
Your assertion is true.
The problem is that it's currently just in the stage-1
, so it's not clear when and if ever it becomes the standard.
References:
- https://github.com/tc39/ecma262
- https://github.com/jeffmo/es-class-fields-and-static-properties
- https://github.com/jeffmo/es-class-fields-and-static-properties#part-1-class-instance-fields
来源:https://stackoverflow.com/questions/35819911/es6-instance-property-instantiated-outside-of-constructor