ES6标准新增了一种新的函数:Arrow Function(箭头函数)。
原来写法:
function (x) {
return x * x;
}
箭头函数写法:
x => x * x
使用ES6箭头函数语法定义函数,将原函数的“function”关键字和函数名都删掉,并使用“=>”连接参数列表和函数体。箭头函数看上去是匿名函数的一种简写,但实际上,箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,由上下文确定。(词法作用域就是定义在词法阶段的作用域。换句话说,词法作用域是由你在写代码时将变量和块作用域写在哪里来决定的,因此当词法分析器处理代码时会保持作用域不变 。)箭头函数的this永远指向其父作用域
举个例子来说明箭头函数和原函数的区别:
let obj = {
birth: 2000,
getAge: function () {
let b = this.birth; // 1990
let fn = function () {
return new Date().getFullYear() - this.birth; // this指向window或undefined
};
return fn();
}
};
console.log(obj.getAge()) //NaN
var obj = {
birth: 2000,
getAge: function () {
let b = this.birth; // 1990
let fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
return fn();
}
};
console.log(obj.getAge()) //22
示例及注意事项:
1、当函数参数只有一个,括号可以省略;但是没有参数时,括号不可以省略。
// 无参
var fn = function() {}
var fn = () => {}
// 单个参数
var fn = function(a) {}
var fn = a => {}
// 多个参数
var fn = function(a, b) {}
var fn = (a, b) => {}
// 可变参数
var fn4 = function(a, b, ...args) {}
var fn4 = (a, b, ...args) => {}
//返回一个对象
2、箭头函数的this永远指向其父作用域,任何方法都改变不了,包括call,apply,bind。
3、箭头函数不能作为构造函数,不能使用new
因为构造函数的this必须是对象实例,而箭头函数的this根据上下文来确定的因此是没有实例的,箭头函数的this指向别处,自相矛盾。
4、箭头函数没有arguments,caller,callee
箭头函数本身没有arguments,如果箭头函数在一个function内部,它会将外部函数的arguments拿过来使用。
箭头函数中要想接收不定参数,应该使用rest参数...解决。
let A = (b)=>{
console.log(arguments);
}
A(1,2,3); // Uncaught ReferenceError: arguments is not defined
let B = (...c) => {
console.log(c);
}
B(1,2,3); // [1,2,3]
5、 箭头函数通过call和apply调用,不会改变this指向,只会传入参数
let obj = {
a: 10,
b: function(n) {
let f = (n) => n + this.a;
return f(n);
},
c: function(n) {
let f = (n) => n + this.a;
let m = {
a: 20
};
return f.call(m,n);
}
};
console.log(obj.b(1)); // 11
console.log(obj.c(1)); // 11
6、 箭头函数没有原型属性
var a = ()=>{
return 1;
}
function b(){
return 1;
}
console.log(a.prototype); // undefined
console.log(b.prototype); // {constructor: ƒ}
7、箭头函数不能作为Generator函数,不能使用yield关键字
8、箭头函数返回对象时,要加一个小括号
var fn = () => ({ a: 1 }); //正确
var fn = () => { a: 1 }; //错误
9、箭头函数在ES6 class中声明的方法为实例方法,不是原型方法
class S{
fn(){
}
}
var a = new S()
var b = new S()
console.log(a.fn === b.fn )//true
class X{
fn=()=>{
}
}
var c = new X()
var d = new X()
console.log(c.fn === d.fn )//false
10、多重箭头函数就是一个高阶函数,相当于内嵌函数
var add = x => y => y + x;
function add(x){
return function(y){
return y + x;
};
}