es6的箭头函数,function* , yeild详解

来源:互联网 发布:淘宝买论文靠谱吗 编辑:程序博客网 时间:2024/04/28 00:00

var f = v => v*2;  借鉴思路与java8的lamada 表达式类似 ,写匿名函数。
// 等价于
var f = function(v){
  return v*2;
}

// 判断偶数
var isEven = n => n % 2 == 0;

// 需要加 return
var = (a, b) => {
  if(a >= b)
    return a;
  return b;
}

 var isNumber= n => isNan(n);
 
 
 1:箭头函数
 
 
 // ES6
function obj() {
  setTimeout(()=>console.log(this.id), 20);
}

// ES5
function foo() {
  var _this = this;
  setTimeout(function () {
    console.log(_this.id);
  }, 20);
}

2:function* yield 迭代器

根据语法规范,yield 关键字用来暂停和继续执行一个生成器函数。当外部调用生成器的 next() 方法时,yield 关键字右侧的表达式才会执行。

执行结果会转化为一个对象(包含两个属性, value 和 done),作为 next() 方法的返回值。

对于  var foo = yield expression 语句,yield 左侧变量 foo 的值将在下一次调用 next() 方法时获得,并且等于调用时 next() 方法的参数。

function* 这种声明方式(function关键字后跟一个星号)会定义一个生成器函数 (generator function),它返回一个  Generator  对象。

 function* generator()
 {
 }
 
 function* g1() {
  yield 2
  yield 3
}

function* g2() {
  yield 1
  yield g1()
  yield* g1()
  yield [4, 5]
  yield* [6, 7]
}

const iterator = g2()

console.log(iterator.next()) // { value: 1, done: false }
console.log(iterator.next()) // { value: {}, done: false }
console.log(iterator.next()) // { value: 2, done: false }
console.log(iterator.next()) // { value: 3, done: false }
console.log(iterator.next()) // { value: [4, 5], done: false }
console.log(iterator.next()) // { value: 6, done: false }
console.log(iterator.next()) // { value: 7, done: false }
console.log(iterator.next()) // { value: undefined, done: true }


class 及继承

//定义类
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
 
  // 注意函数构造的方式
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
 
}
var p1 = new Point(5, 5);
p1.toString(); //"(5, 5)"

typeof Point // function
p1.constructor == Point //tru

直接使用 class 关键字,constructor 作为构造方法,函数可以直接 toString(){} 的方式。

但是,class 的本质仍然是函数,是构造函数的另外一种写法。既然 class 的本质是函数,那么必不可少的一些 proto,prototype 方法也是存在的。
 


原创粉丝点击