您的位置:首页 > Web前端 > JavaScript

ES6箭头函数(Arrow Functions)

2016-10-06 14:56 423 查看

箭头函数是什么?(What)

箭头函数 (Arrow Functions)也称“胖箭头函数”,是ES6全新的特性。是个简写的函数表达式,拥有词法作用域的
this
。此外,箭头函数总是匿名的。(词法作用域就是一个变量的作用在定义的时候就已经被定义好,当在本作用域中找不到变量,就会一直向父作用域中查找,直到找到为止。)

箭头函数的语法(How)

()=>{return 1;}

函数无参数,返回值为1

(x)=>x*x;

返回值为参数的平方,当函数体只有一条语句时,则可以省略大括号{},默认返回该表达式的值。

x=>x*x;

只有一个参数时,则可以省略小括号()

()=>{……return 1;}

返回值为1。(使用块语句的箭头函数不会自动返回值,需要使用return语句将所需的值返回)

()=>({})

返回值为对象

箭头函数的特性

1、typeof运算符和普通的函数一样

let commFunc = () => {};
console.log(typeof commFunc);


输出为
function


let arrowFunc = () => {};
console.log(typeof arrowFunc);


输出也为
function


从此可以看出箭头函数的类型和普通的函数一样都为
function


2、
instanceof
也返回
true
,表明是Function的实例

let func = () => {};
console.log(func instanceof Function);


输出为
true
,由此可以看出箭头函数也是Function的实例

3、箭头函数中的
this
继承外围作用域

let person = {
name: "galler",
say: () => {
console.log(this);
console.log(this.name);
}
};
person.say();


this
的值为”{}”或
window
this.name
的值为
undefined
或”“(空字符串)。将上面的这段代码写在文件中,在node环境中运行,
this
的值输出为”{}”,这个空对象就是
exports
,因为没有写
exports
exports
就默认指向
module.exports
,而
module.exports
就是个空对象。但是在命令行中运行上面代码(依然是node环境中),则
this
指向
global
对象(这些有可能偏离中心,但是大家可以试试,在这段代码前加上
exports.name = "susan"
,此时的
this
指向
{"name","susan"}
对象,
this.name
的值就是
susan


let person = {
name: "galler",
speak: function() {
console.log(this); //person对象。
console.log(this.name); //galler
}
};
person.speak();


this
的值为person对象,
this.name
的值为galler。

小结:箭头函数本身没有
this
,根据词法作用域,于是向上查找
this
,则发现
this
指向
window
对象(浏览器环境)或者{}(Node环境中),由于
window
和{}对象没有
name
属性,则
this.name
为”“(浏览器环境)或者
undefined
(Node环境)

4、返回对象用小括号括起来

let person = () => {
name:"galler"
}
console.log(person());


输出为
undefined
。此时的”{}”表明函数的起始位置和结束位置,由于该函数没有返回值,所以被调用时值为undefined

let person = () => ({
name:"galler"
});
console.log(person());


输出为
{name:"galler"}
。 此时”{}”表示定义一个对象。用”()”括起来表示是一个表达式,默认返回该对象。

5、箭头函数中不能使用
new


let Person = (name) => {
this.name = name;
};
let one = new Person("galler");


运行该程序,则出现
TypeError: Person is not a constructor


6、arguments

function person() {
console.log(arguments);
}
person(1);


一般的函数使用
arguments
,在浏览器中输出为一个数组:
[1]
,在Node环境中输出为一个对象:
{'0':1}


let person = () => {
console.log(arguments);
};
person("galler");


箭头函数使用
arguments
,在浏览器环境中,则出现
ReferenceError
,在Node环境中输出
{"0":{},……}


由此可以得出,箭头函数与普通函数的再一个区别:不能使用
arguments
对象。

7、没有原型

let person = () => {}
console.log(person.prototype);


输出为
undefined
。由此可以看出箭头函数没有原型。

箭头函数产生的目的

简洁语法

与父作用域共享关键字
this


箭头函数的优点

使用箭头函数比普通函数少些动词,如:
function
return


this
提前定义,从上下文可以捕获
this


注意:箭头函数内容实体中不能使用statement作为表达式expression。

事物都是有两面性的,所以箭头函数的优点即缺点。代码太过简单,导致不好阅读,
this
提前定义。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息