码迷,mamicode.com
首页 > 其他好文 > 详细

ES6的新特性

时间:2017-03-21 12:58:17      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:...   for   define   rip   span   特性   恢复   res   read   

---恢复内容开始---

1.箭头函数 

1 var arr = [1,2,3];
2         //传统写法 
3 arr.forEach( function(val, index) {
4     console.log(index + ‘ ‘ + val+‘,‘)//0 1,1 2,2 3
5 });
6         //es6
7 arr.forEach((val,index) => console.log(index + ‘ ‘ + val)); //0 1,1 2,2 3

2.类的支持

 1 class People  {
 2     constructor(name=‘jack‘){ //默认参数
 3         this.name = name; // this.name = name||‘jack‘传统默认参数
 4     }
 5     sayHello() {
 6         console.log(`my name is ${this.name}`) //字符串模版 反向‘
 7     }
 8 }
 9 class Student extends People{   //extends Es6 继承
10     constructor(name) {
11         super(name);
12     }
13     doSth() {
14         console.log(‘I am doing homework‘)
15     }
16 }
17 var noname = new Student();
18 var leonel = new Student(‘leonel‘);
19 noname.sayHello();//my name is jack
20 leonel.sayHello();//my name is leonel
21 leonel.doSth();//I am doing homework

3.解构

1 var  [x,y] = getVal(),
2     [name,,sex]=[‘leonel‘,25,‘man‘];
3 function getVal() {
4     return [0,1];
5 }
6 console.log(‘x:‘+x+‘   y:‘+y)//x:0 y:1
7 console.log(‘name:‘+name+‘   sex:‘+sex) //name:leonel  sex:man

4.不定参数

function print1(...x) { //...x 相当于arguments
    for(let v of x) {     //for of 遍历数组,类似于for in  区别:for in 遍历的是key,for of 遍历的是value
        console.log(v) 
    }
}
function print2(arguments) { //...x 相当于arguments
    for ( let i in arguments ){  //let 定义局部变量 只有 当前体内才能使用
        console.log(i)   
    }
    //console.log(i) //报错  i is undefined
}
var arr = [‘one‘,‘two‘,‘three‘];
print1(...arr) // one two three 
//传统写法print1(‘one‘,‘two‘,‘three‘)
print2(...arr) // 0  1 2 

5.Proxies

1 var enginner = {name: ‘leonel‘,age:25}; //被监听的对象
2 var doProcess ={
3     set:function(received,property,value){
4         console.log(property +"  is changed");
5         received[property] = value;
6     }
7 }
8 enginner = new Proxy(enginner,doProcess); //new 一个proxy  doprocess 监听 enginner 上发生改变了什么
9 enginner.age=40; //age is changed

 6.Promise 

 1 //创建promise
 2 var promise = new Promise(function(resolve, reject) {
 3     // 进行一些异步或耗时操作
 4     if ( /*如果成功 */ ) {
 5         resolve("Stuff worked!");
 6     } else {
 7         reject(Error("It broke"));
 8     }
 9 });
10 //绑定处理程序
11 promise.then(function(result) {
12     //promise成功的话会执行这里
13     console.log(result); // "Stuff worked!"
14 }, function(err) {
15     //promise失败会执行这里
16     console.log(err); // Error: "It broke"
17 })

 ------未完-----------

参考于博客ES6新特性概览阮老师的ECMAScript 6 入门

ES6的新特性

标签:...   for   define   rip   span   特性   恢复   res   read   

原文地址:http://www.cnblogs.com/leonel/p/6593477.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!