es6新语法

来源:互联网 发布:网络机顶盒看直播 编辑:程序博客网 时间:2024/05/17 03:15

iteratos: 迭代
{value:xx ,done: true/false}
next//返回一个对象{value:xx ,done: true/false},如果没有值的话则返回{value: undefined,done:true}

‘use strict’;

funciton chef(foods) {
let i =0;

return { next () {   let done = (i >= foods.length);   let value = !done ? food[i++] :undefined;   return {     value: value,     done: done   } }}

}

let wanghao = chef([‘a’,b]);
console.log(wanghao.next()); // {value: a,done:false}
console.log(wanghao.next()); // {value: b,done:false}
console.log(wanghao.next()); // {value: undefined,done:true}

generator
生成迭代器
function* chef() { //定义生成器
yield “a”;
yield “b”;
}

let wanghao = chef();

console.log(wanghao.next()); // {value: a,done:false}
console.log(wanghao.next()); // {value: b,done:false}
console.log(wanghao.next()); // {value: undefined,done:true}

classes

‘use strict’;

class Chef { //定义一个类
construtor(food) { // 构造方法
this.food = food;
}

cook() {  console.log(this.food);}

}

let wanghao = new Chef(‘a’);
wanghao.cook(); //调用定义的方法,返回是’a’

get/set

‘use strict’;

class Chef { //定义一个类
construtor(food) { // 构造方法
this.food = food;
this.dish = [];
}

 get menu () {  return this.dish; } set menu () { this.dish.push(dish); }cook() {  console.log(this.food);}

}

let wanghao = new Chef();
console.log(wanghao.menu = ‘a’);//a
console.log(wanghao.menu = ‘b’);//b
console.log(wanghao.menu);//a,b

static //静态方法

‘use strict’;

class Chef { //定义一个类
construtor(food) { // 构造方法
this.food = food;
this.dish = [];
}

 get menu () {  return this.dish; } set menu () { this.dish.push(dish); }static cook(food) { //(把传递到方法的值传递到控制台上)  console.log(food);}

}

Chef.cook(‘a’);//a

extends//继承

‘use strict’;

class Person {
constructor(name, birthday) {
this.name = name;
this.birthday = birthday;
}

intro () { return `${this.name}, ${this.birthday}`;}

}

class Chef extends Person {
constructor(name, birthday) {
super(name, birthday);
}
}

let wanghao = new Chef(‘wanghao’, ‘1984-1-01’);
consoel.log(wanghao.intro);// ‘wanghao’, ‘1984-1-01’

set//集合(里面不能重复的)

let desserts = new Set(‘abc’);
desserts.add(‘d’);//Set{abcd}
desserts.add(‘d’);//Set{abcd}(不会添加重复的东西)

console.log(desserts);
console.log(desserts.size); // 集合的长度
console.log(desserts.has(‘b’));//true (判断是否存在b这个元素)
console.log(desserts.delete(‘b’));//Set{acd}(删除这个元素)
desserts.forEach(dessert => {
console.log(dessert);
});
desserts.clear();//Set{}清空集合

Map
‘use strict’;
let food = new Map();
let fruit = {}, cook = function() {}, dessert= ‘甜点’;

food.set(fruit, ‘a’);
food.set(cook, ‘b’);//

原创粉丝点击