【笔记】箭头函数

前言

本文摘录自《understanding ECMAScript6》的第三章——函数,主要内容包括:箭头函数与传统函数的差异、语法、利用箭头函数创建立即执行函数、箭头函数中的this等等

箭头函数与传统函数的差异

  • 没有this、super、arguments,也没有new.target绑定:它们的值由所在的、最靠近的非箭头函数来决定
  • 不能被new调用:箭头函数没有[[constructor]]方法,不能被当作构造函数被new调用
  • 没有原型:没有prototype属性
  • 不能更改this:this的值由包含它的函数决定,在函数的整个生命周期内其值不变
  • 没有arguments对象:箭头函数没有arguments绑定,必须依赖形参或剩余参数来访问函数的参数
  • 不允许重复的形参:无论严格模式还是非严格模式,都不允许出现重复的形参

语法

单个参数时,省略括号

      
      
1
2
3
4
5
6
7
      
      
let func = value => value
// es5
var func = function(value) {
return value;
}

多个参数、无参数时,需要括号

      
      
1
2
3
4
5
6
      
      
let sum = (num1, num2) => num1 + num2;
// es5
var sum = function(num1, num2) {
return num1 + num2;
}
      
      
1
2
3
4
5
6
      
      
let getName = () => 'Nicholas';
// es5
var getName = function() {
return 'Nicholas';
}

创建空函数

      
      
1
      
      
let doNothing = () => {}

返回对象字面量:把对象字面量包裹在括号内,表示括号内是一个字面量而不是函数体

      
      
1
2
3
4
5
6
7
8
9
      
      
let getObj = id => ({ id, name: 'u14e' });
// es5
var getObj = function(id) {
return {
id: id,
name: 'u14e'
}
}

注意:上面的箭头函数都是没有使用花括号的,这种情况下js引擎默认添加了return。而使用花括号后,需要手动添加return语句,如果没加,函数将不返回值

创建立即执行函数

使用传统函数时,(function(){})()、(function(){}())都可以,而箭头函数只支持(() => {})();

      
      
1
2
3
4
      
      
let person = ( name => ({
getName: function() { 大专栏  【笔记】箭头函数d">return name }
}))( 'Nicholas');
console.log(person.getName()); // Nicholas

没有this绑定

传统函数中的this可以被改变,其值取决于调用该函数时的上下文

      
      
1
2
3
4
5
6
7
8
9
10
11
      
      
var pageHandler = {
id: '123456',
init: function() {
document.addEventListener( 'click', function(event) {
this.doSomething(event.type); // 报错,因为this指向的时document,而不是pageHandler
}, false);
},
doSomething: function(type) {
console.log(type);
}
}

使用bind()方法

      
      
1
2
3
4
5
6
7
8
9
10
11
      
      
var pageHandler = {
id: '123456',
init: function() {
document.addEventListener( 'click', function(event) {
this.doSomething(event.type);
}.bind( this), false);
},
doSomething: function(type) {
console.log(type);
}
}

箭头函数没有this绑定,this只能通过查找作用域来确定。如果箭头函数被包含在一个非箭头函数内,那么this就与该函数的this相等;否则,this值为undefined

      
      
1
2
3
4
5
6
7
8
9
10
11
      
      
var pageHandler = {
id: '123456',
init: function() {
document.addEventListener( 'click', event => {
this.doSomething(event.type);
}, false);
},
doSomething: function(type) {
console.log(type);
}
}

注意:由于箭头函数的this值由包含它的函数决定,因此不能使用call、apply、bind方法来改变this值

没有arguments对象

虽然箭头函数没有自己的arguments对象,但是可以访问包含它的函数的arguments对象

      
      
1
2
3
4
5
6
7
      
      
function () {
return () => arguments[ 0];
}
var func = foo( 3);
console.log(func()); // 3

猜你喜欢

转载自www.cnblogs.com/dajunjun/p/11713236.html