• 首页

  • 归档

  • 标签

  • 分类

  • 友链
M S B l o g
M S B l o g

ms

获取中...

05
29
总结
教程
javascript

ES6:箭头函数

发表于 2021-05-29 • 总结 前端 ES6 javascript • 被 933 人看爆

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;
}
分享到:
Vue生命周期及钩子函数
Spring Cloud Gateway
  • 文章目录
  • 站点概览
ms

MSms

⚓️HelloWorld⚓️

QQ Email RSS
看爆 Top5
  • MyBatis-Plus分页查询 5,937次看爆
  • @Autowired与@Resource的区别 4,755次看爆
  • feign远程调用及异步调用丢失请求头问题 4,526次看爆
  • spring cloud中OpenFeign整合Sentinel启动报错 4,423次看爆
  • Certbot查看证书过期时间,手动续期以及自动续期 3,302次看爆

Copyright © 2025 ms · 湘ICP备20015239号

Proudly published with Halo · Theme by fyang · 站点地图