JavaScript【ES5、ES6】版本寫法對照表
阿新 • • 發佈:2019-01-06
學習ES6的動機是因為公司要使用 React Native(以下簡稱RN),由於RN使用了ES6的新語法,所以要學習ES6的新語法。
以下列出 ES5 與 ES6 的對比寫法,來讓大家學習一些新的寫法。
強烈建議大家系統的學習一下JavaScript。
//React/React Native 的ES5 ES6寫法對照表
//
//很多React/React Native的初學者都被ES6的問題迷惑:各路大神都建議我們直接學習ES6的語法(class Foo extends React.Component),然而網上搜到的很多教程和例子都是ES5版本的,所以很多人在學習的時候連照貓畫虎都不知道怎麼做。今天在此整理了一些ES5和ES6的寫法對照表,希望大家以後讀到ES5的程式碼,也能通過對照,在ES6下實現相同的功能。
//
//模組
//引用
//在ES5裡,如果使用CommonJS標準,引入React包基本通過require進行,程式碼類似這樣:
//ES5
var React = require("react-native");
var {
Image,
Text,
PropTypes
} = React; //引用不同的React Native元件
//在ES6裡,import寫法更為標準
//ES6
import React, {
Image,
Text,
PropTypes
} from 'react-native';
//注意在React Native裡,import直到0.12+才能正常運作。 //匯出單個類
//在ES5裡,要匯出一個類給別的模組用,一般通過module.exports來匯出
//ES5
var MyComponent = React.createClass({
...
});
module.exports = MyComponent;
//在ES6裡,通常用export default來實現相同的功能:
//ES6
export default class MyComponent extends React.Component{
... } //引用的時候也類似: //ES5
var MyComponent = require('./MyComponent.js');
//ES6
import MyComponent from './MyComponent.js';
//定義元件
//在ES5裡,通常通過React.createClass來定義一個元件類,像這樣:
//ES5
var Photo = React.createClass({
render: function() {
return (
<Image source={this.props.source} />
);
}, }); //在ES6裡,我們通過定義一個繼承自React.Component的class來定義一個元件類,像這樣: //ES6
class Photo extends React.Component {
render() {
return (
<Image source={this.props.source} />
);
}
}
//給元件定義方法
//從上面的例子裡可以看到,給元件定義方法不再用 名字: function()的寫法,而是直接用名字(),在方法的最後也不能有逗號了。
//ES5
var Photo = React.createClass({
componentWillMount: function(){
},
render: function() {
return (
<Image source={this.props.source} />
);
},
});
//ES6
class Photo extends React.Component {
componentWillMount() {
}
render() {
return (
<Image source={this.props.source} />
);
} } //定義元件的屬性型別和預設屬性
//在ES5裡,屬性型別和預設屬性分別通過propTypes成員和getDefaultProps方法來實現
//ES5
var Video = React.createClass({
getDefaultProps: function() {
return {
autoPlay: false,
maxLoops: 10,
};
},
propTypes: {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
},
render: function() {
return (
<View />
);
}, }); //在ES6裡,可以統一使用static成員來實現 //ES6
class Video extends React.Component {
static defaultProps = {
autoPlay: false,
maxLoops: 10,
}
static propTypes = {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
}
render() {
return (
<View />
);
}
} //也有人這麼寫,雖然不推薦,但讀到程式碼的時候你應當能明白它的意思: //ES6
class Video extends React.Component {
render() {
return (
<View />
);
}
}
Video.defaultProps = {
autoPlay: false,
maxLoops: 10,
};
Video.propTypes = {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired, }; //注意: 對React開發者而言,static成員在IE10及之前版本不能被繼承,而在IE11和其它瀏覽器上可以,這有時候會帶來一些問題。React Native開發者可以不用擔心這個問題。
//初始化state
//ES5下情況類似,
//ES5
var Video = React.createClass({
getInitialState: function() {
return {
loopsRemaining: this.props.maxLoops,
};
},
})
//ES6下,有兩種寫法:
//ES6
class Video extends React.Component {
state = {
loopsRemaining: this.props.maxLoops,
}
}
//不過我們推薦更易理解的在建構函式中初始化(這樣你還可以根據需要做一些計算):
//ES6
class Video extends React.Component {
constructor(props){
super(props);
this.state = {
loopsRemaining: this.props.maxLoops,
};
} } //把方法作為回撥提供
//很多習慣於ES6的使用者反而不理解在ES5下可以這麼做:
//ES5
var PostInfo = React.createClass({
handleOptionsButtonClick: function(e) {
// Here, 'this' refers to the component instance.
this.setState({showOptionsModal: true});
},
render: function(){
return (
<TouchableHighlight onPress={this.handleOptionsButtonClick}>
<Text>{this.props.label}</Text>
</TouchableHighlight>
)
},
});
//在ES5下,React.createClass會把所有的方法都bind一遍,這樣可以提交到任意的地方作為回撥函式,而this不會變化。但官方現在逐步認為這反而是不標準、不易理解的。
//在ES6下,你需要通過bind來繫結this引用,或者使用箭頭函式(它會綁定當前scope的this引用)來呼叫
//ES6
class PostInfo extends React.Component
{
handleOptionsButtonClick(e){
this.setState({showOptionsModal: true});
}
render(){
return (
<TouchableHighlight
onPress={this.handleOptionsButtonClick.bind(this)}
onPress={e=>this.handleOptionsButtonClick(e)}
>
<Text>{this.props.label}</Text>
</TouchableHighlight>
)
}, } //箭頭函式實際上是在這裡定義了一個臨時的函式,箭頭函式的箭頭=>之前是一個空括號、單個的引數名、或用括號括起的多個引數名,而箭頭之後可以是一個表示式(作為函式的返回值),或者是用花括號括起的函式體(需要自行通過return來返回值,否則返回的是undefined)。
// 箭頭函式的例子
()=>1
v=>v+1
(a,b)=>a+b
()=>{
alert("foo");
}
e=>{
if (e == 0){
return 0;
}
return 1000/e;
}
//需要注意的是,不論是bind還是箭頭函式,每次被執行都返回的是一個新的函式引用,因此如果你還需要函式的引用去做一些別的事情(譬如解除安裝監聽器),那麼你必須自己儲存這個引用
// 錯誤的做法
class PauseMenu extends React.Component{
componentWillMount(){
AppStateIOS.addEventListener('change', this.onAppPaused.bind(this));
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change', this.onAppPaused.bind(this));
}
onAppPaused(event){
}
}
// 正確的做法
class PauseMenu extends React.Component{
constructor(props){
super(props);
this._onAppPaused = this.onAppPaused.bind(this);
}
componentWillMount(){
AppStateIOS.addEventListener('change', this._onAppPaused);
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change', this._onAppPaused);
}
onAppPaused(event){
}
}
//從這個帖子中我們還學習到一種新的做法:
// 正確的做法
class PauseMenu extends React.Component{
componentWillMount(){
AppStateIOS.addEventListener('change', this.onAppPaused);
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change', this.onAppPaused);
}
onAppPaused = (event) => {
//把方法直接作為一個arrow function的屬性來定義,初始化的時候就繫結好了this指標
} } //Mixins
//在ES5下,我們經常使用mixin來為我們的類新增一些新的方法,譬如PureRenderMixin
var PureRenderMixin = require('react-addons-pure-render-mixin');
React.createClass({
mixins: [PureRenderMixin],
render: function() {
return <div className={this.props.className}>foo</div>;
}
});
//然而現在官方已經不再打算在ES6裡繼續推行Mixin,他們說:Mixins Are Dead. Long Live Composition。
//儘管如果要繼續使用mixin,還是有一些第三方的方案可以用,譬如這個方案
//不過官方推薦,對於庫編寫者而言,應當儘快放棄Mixin的編寫方式,上文中提到Sebastian Markbåge的一段程式碼推薦了一種新的編碼方式:
//Enhance.js
import { Component } from "React";
export var Enhance = ComposedComponent => class extends Component {
constructor() {
this.state = { data: null };
}
componentDidMount() {
this.setState({ data: 'Hello' });
}
render() {
return <ComposedComponent {...this.props} data={this.state.data} />;
}
};
//HigherOrderComponent.js
import { Enhance } from "./Enhance";
class MyComponent {
render() {
if (!this.data) return <div>Waiting...</div>;
return <div>{this.data}</div>;
}
}
export default Enhance(MyComponent); // Enhanced component
//用一個“增強函式”,來某個類增加一些方法,並且返回一個新類,這無疑能實現mixin所實現的大部分需求。 //ES6+帶來的其它好處
//解構&屬性延展 ###
//結合使用ES6+的解構和屬性延展,我們給孩子傳遞一批屬性更為方便了。這個例子把className以外的所有屬性傳遞給div標籤:
class AutoloadingPostsGrid extends React.Component {
render() {
var {
className,
...others, // contains all properties of this.props except for className
} = this.props;
return (
<div className={className}>
<PostsGrid {...others} />
<button onClick={this.handleLoadMoreClick}>Load more</button>
</div>
);
}
}
//下面這種寫法,則是傳遞所有屬性的同時,用覆蓋新的className值:
<div {...this.props} className="override"></div>
//這個例子則相反,如果屬性中沒有包含className,則提供預設的值,而如果屬性中已經包含了,則使用屬性中的值
//
//很多React/React Native的初學者都被ES6的問題迷惑:各路大神都建議我們直接學習ES6的語法(class Foo extends React.Component),然而網上搜到的很多教程和例子都是ES5版本的,所以很多人在學習的時候連照貓畫虎都不知道怎麼做。今天在此整理了一些ES5和ES6的寫法對照表,希望大家以後讀到ES5的程式碼,也能通過對照,在ES6下實現相同的功能。
//模組
//引用
//在ES5裡,如果使用CommonJS標準,引入React包基本通過require進行,程式碼類似這樣:
//ES5
var React = require("react-native");
var {
Image,
Text,
PropTypes
} = React; //引用不同的React Native元件
//在ES6裡,import寫法更為標準
//ES6
import React, {
Image,
Text,
PropTypes
} from 'react-native';
//注意在React Native裡,import直到0.12+才能正常運作。 //匯出單個類
//ES5
var MyComponent = React.createClass({
...
});
module.exports = MyComponent;
//在ES6裡,通常用export default來實現相同的功能:
//ES6
export default class MyComponent extends React.Component{
... } //引用的時候也類似: //ES5
var MyComponent = require('./MyComponent.js');
//ES6
import MyComponent from
//定義元件
//在ES5裡,通常通過React.createClass來定義一個元件類,像這樣:
//ES5
var Photo = React.createClass({
render: function() {
return (
<Image source={this.props.source} />
);
}, }); //在ES6裡,我們通過定義一個繼承自React.Component的class來定義一個元件類,像這樣: //ES6
class Photo extends React.Component {
render() {
return (
<Image source={this.props.source} />
);
}
}
//給元件定義方法
//從上面的例子裡可以看到,給元件定義方法不再用 名字: function()的寫法,而是直接用名字(),在方法的最後也不能有逗號了。
//ES5
var Photo = React.createClass({
componentWillMount: function(){
},
render: function() {
return (
<Image source={this.props.source} />
);
},
});
//ES6
class Photo extends React.Component {
componentWillMount() {
}
render() {
return (
<Image source={this.props.source} />
);
} } //定義元件的屬性型別和預設屬性
//在ES5裡,屬性型別和預設屬性分別通過propTypes成員和getDefaultProps方法來實現
//ES5
var Video = React.createClass({
getDefaultProps: function() {
return {
autoPlay: false,
maxLoops: 10,
};
},
propTypes: {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
},
render: function() {
return (
<View />
);
}, }); //在ES6裡,可以統一使用static成員來實現 //ES6
class Video extends React.Component {
static defaultProps = {
autoPlay: false,
maxLoops: 10,
}
static propTypes = {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
}
render() {
return (
<View />
);
}
} //也有人這麼寫,雖然不推薦,但讀到程式碼的時候你應當能明白它的意思: //ES6
class Video extends React.Component {
render() {
return (
<View />
);
}
}
Video.defaultProps = {
autoPlay: false,
maxLoops: 10,
};
Video.propTypes = {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired, }; //注意: 對React開發者而言,static成員在IE10及之前版本不能被繼承,而在IE11和其它瀏覽器上可以,這有時候會帶來一些問題。React Native開發者可以不用擔心這個問題。
//初始化state
//ES5下情況類似,
//ES5
var Video = React.createClass({
getInitialState: function() {
return {
loopsRemaining: this.props.maxLoops,
};
},
})
//ES6下,有兩種寫法:
//ES6
class Video extends React.Component {
state = {
loopsRemaining: this.props.maxLoops,
}
}
//不過我們推薦更易理解的在建構函式中初始化(這樣你還可以根據需要做一些計算):
//ES6
class Video extends React.Component {
constructor(props){
super(props);
this.state = {
loopsRemaining: this.props.maxLoops,
};
} } //把方法作為回撥提供
//很多習慣於ES6的使用者反而不理解在ES5下可以這麼做:
//ES5
var PostInfo = React.createClass({
handleOptionsButtonClick: function(e) {
// Here, 'this' refers to the component instance.
this.setState({showOptionsModal: true});
},
render: function(){
return (
<TouchableHighlight onPress={this.handleOptionsButtonClick}>
<Text>{this.props.label}</Text>
</TouchableHighlight>
)
},
});
//在ES5下,React.createClass會把所有的方法都bind一遍,這樣可以提交到任意的地方作為回撥函式,而this不會變化。但官方現在逐步認為這反而是不標準、不易理解的。
//在ES6下,你需要通過bind來繫結this引用,或者使用箭頭函式(它會綁定當前scope的this引用)來呼叫
//ES6
class PostInfo extends React.Component
{
handleOptionsButtonClick(e){
this.setState({showOptionsModal: true});
}
render(){
return (
<TouchableHighlight
onPress={this.handleOptionsButtonClick.bind(this)}
onPress={e=>this.handleOptionsButtonClick(e)}
>
<Text>{this.props.label}</Text>
</TouchableHighlight>
)
}, } //箭頭函式實際上是在這裡定義了一個臨時的函式,箭頭函式的箭頭=>之前是一個空括號、單個的引數名、或用括號括起的多個引數名,而箭頭之後可以是一個表示式(作為函式的返回值),或者是用花括號括起的函式體(需要自行通過return來返回值,否則返回的是undefined)。
// 箭頭函式的例子
()=>1
v=>v+1
(a,b)=>a+b
()=>{
alert("foo");
}
e=>{
if (e == 0){
return 0;
}
return 1000/e;
}
//需要注意的是,不論是bind還是箭頭函式,每次被執行都返回的是一個新的函式引用,因此如果你還需要函式的引用去做一些別的事情(譬如解除安裝監聽器),那麼你必須自己儲存這個引用
// 錯誤的做法
class PauseMenu extends React.Component{
componentWillMount(){
AppStateIOS.addEventListener('change', this.onAppPaused.bind(this));
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change', this.onAppPaused.bind(this));
}
onAppPaused(event){
}
}
// 正確的做法
class PauseMenu extends React.Component{
constructor(props){
super(props);
this._onAppPaused = this.onAppPaused.bind(this);
}
componentWillMount(){
AppStateIOS.addEventListener('change', this._onAppPaused);
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change', this._onAppPaused);
}
onAppPaused(event){
}
}
//從這個帖子中我們還學習到一種新的做法:
// 正確的做法
class PauseMenu extends React.Component{
componentWillMount(){
AppStateIOS.addEventListener('change', this.onAppPaused);
}
componentDidUnmount(){
AppStateIOS.removeEventListener('change', this.onAppPaused);
}
onAppPaused = (event) => {
//把方法直接作為一個arrow function的屬性來定義,初始化的時候就繫結好了this指標
} } //Mixins
//在ES5下,我們經常使用mixin來為我們的類新增一些新的方法,譬如PureRenderMixin
var PureRenderMixin = require('react-addons-pure-render-mixin');
React.createClass({
mixins: [PureRenderMixin],
render: function() {
return <div className={this.props.className}>foo</div>;
}
});
//然而現在官方已經不再打算在ES6裡繼續推行Mixin,他們說:Mixins Are Dead. Long Live Composition。
//儘管如果要繼續使用mixin,還是有一些第三方的方案可以用,譬如這個方案
//不過官方推薦,對於庫編寫者而言,應當儘快放棄Mixin的編寫方式,上文中提到Sebastian Markbåge的一段程式碼推薦了一種新的編碼方式:
//Enhance.js
import { Component } from "React";
export var Enhance = ComposedComponent => class extends Component {
constructor() {
this.state = { data: null };
}
componentDidMount() {
this.setState({ data: 'Hello' });
}
render() {
return <ComposedComponent {...this.props} data={this.state.data} />;
}
};
//HigherOrderComponent.js
import { Enhance } from "./Enhance";
class MyComponent {
render() {
if (!this.data) return <div>Waiting...</div>;
return <div>{this.data}</div>;
}
}
export default Enhance(MyComponent); // Enhanced component
//用一個“增強函式”,來某個類增加一些方法,並且返回一個新類,這無疑能實現mixin所實現的大部分需求。 //ES6+帶來的其它好處
//解構&屬性延展 ###
//結合使用ES6+的解構和屬性延展,我們給孩子傳遞一批屬性更為方便了。這個例子把className以外的所有屬性傳遞給div標籤:
class AutoloadingPostsGrid extends React.Component {
render() {
var {
className,
...others, // contains all properties of this.props except for className
} = this.props;
return (
<div className={className}>
<PostsGrid {...others} />
<button onClick={this.handleLoadMoreClick}>Load more</button>
</div>
);
}
}
//下面這種寫法,則是傳遞所有屬性的同時,用覆蓋新的className值:
<div {...this.props} className="override"></div>
//這個例子則相反,如果屬性中沒有包含className,則提供預設的值,而如果屬性中已經包含了,則使用屬性中的值
<div className="base" {...this.props}></div>
最後祝你避開坑,完成自己所求。