ES6:箭头函数

pmsa
1088
2021-05-29

ES6 允许使用“箭头”(=>)定义函数。类似于java8中的Lambda表达式

使用

var print = function(obj){
	console.log(obj); 
}

等同于
var print = obj => console.log(obj);

  • 当传单个参数的时候,不需要加括号()
var fn = a => a;
  • 当传多个值的时候需要加括号
var fn = (a, b) => a + b;
  • 如果箭头函数的代码块部分多于一条语句,就要使用大括号将它们括起来,并且使用return语句返回。
var sum = (num1, num2) => { 
	num3 = num1 + num2
	return num1 + num3; 
}
  • 箭头函数可以与变量解构结合使用
const person = {
	name: 'jack',
	age: 18,
	language: ['java','js','css']
}

//原写法
function hello(person){
	console.log("hello" + person.name);
}

//使用箭头函数+解构
var hello2 = ({name}) => console.log("hello," + name);

hello2(person);

注意事项:

箭头函数不能用于构造函数

构造函数

var ful=function(age){
    this.age=age;
}
var chl=new ful(18);
console.log(chl.age);//18

使用箭头函数后

var ful = age => {
    this.age=age;
}
var chl=new ful(18);
console.log(chl.age);

结果
image.png

箭头函数没有prototype属性

var fn = () => {};
console.log(fn.prototype); // undefined

箭头函数不绑定this

箭头函数中没有this 的指向,在箭头函数中this 的指向会指向离他最近的那个作用域

var id = 21;

function foo() {
  setTimeout(function() {
    console.log('id:', this.id);
  }, 100);
}

function foo1() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

foo.call({ id: 42 });// 21 普通函数 foo函数中this指向window
foo1.call({id:42});// 42 箭头函数 foo1函数中this指向{id:42}对象

不可以使用yield命令

不可以使用yield命令,因此箭头函数不能用作 Generator 函数。
yield 是 ES6 的新关键字,类似于 return,用于返回一个迭代器(Iterator)对象,它有两个属性,value 和 done,分别代表返回值和是否完成迭代。

function* g() {
  yield 1;
  yield 2;
  yield 3;
}

const iterator = g()
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }

如果将函数 g 写成箭头函数将报错。

var g = () => {
	yield 1;
	yield 2;
	yield 3;
}
动物装饰