ES6今年开始学的,从看文档到实践,以下是自己使用过的一些ES6的东西:
1:for-of 语法:
最喜欢的还是它支持了break/continue的语法,而且还修改了for-in的缺陷,简要写法:
for(let item of dataList){}
2:箭头函数 Arrow Function =>
在
let itemList = (pageData || []).map((item, index)=>{
return (
<PageDataTbody key={index} data={item} />
);
});
箭头函数内部没有 constructor 和 prototype,所以不支持 new 操作,也不支持arguments
比如:
new (() => {}) //VM264:1 Uncaught TypeError: (intermediate value) is not a constructor(…)
3:es6 终于有了类 class的含义
JavaScript语言的传统方法是通过构造函数,定义并生成新对象
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);
ES6提供了更接近传统语言的写法,引入了Class(类)这个概念
//定义类
class Point {
constructor(props) {
super(props);
this.state = {
visible: false
}
}
componentDidMount() {
this.props.actions.getFlowData && this.props.actions.getFlowData(data);
}
}
可以看到里面有一个constructor方法,这就是构造方法,而this关键字则代表实例对象
4: Class的继承:
class ColorPoint extends Point {}
super关键字,它在这里表示父类的构造函数,用来新建父类的this对象。
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y); // 调用父类的constructor(x, y)
this.color = color;
}
toString() {
return this.color + ' ' + super.toString(); // 调用父类的toString()
}
}
子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
大多数浏览器的ES5实现之中,每一个对象都有proto属性,指向对应的构造函数的prototype属性。
class A {
}
class B extends A {
}
B.__proto__ === A // true
B.prototype.__proto__ === A.prototype // true
5:展开运算符
在在多个参数(用于函数调用)或者多个元素(用于数组字面量)或者多个变量(用于解构赋值)的地方使用,使用姿势如下
myFunction(...iterableObj);
var parts = ['shoulder', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes']; // ["head", "shoulders", "knees", "and", "toes"]
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);
6:promise对象
之前有专门写过promise的分享,这里就不展开,贴一段写过的代码
export function refreshGraph(data, compareData) {
return (dispatch, getState)=> {
let getDataFunc = function(data) {
return new Promise(function(resolve, reject){
if(!data) {
return resolve(null);
}
return requestJsonp({
url: 'http://...'
data: data,
method: 'jsonp'
}, json=>{
resolve(json);
}, err=>{
resolve(null);
});
});
};
return Promise.all([getDataFunc(data), getDataFunc(compareData)]).then((json)=>{
if(!json[0] && !json[1]) {
dispatch({
type: DATA_ERR
});
} else {
dispatch({
type: REFRESH_GRAPH,
data: json[0] && json[0].data[data.chartType]
});
}
});
};
}
7:简单的比如let、const就不提了,解构等上面的例子也都有用到