箭头性函数的一些特征和注意事项

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的值为"{}"或windowthis.name的值为undefined或""(空字符串)。将上面的这段代码写在文件中,在node环境中运行,this的值输出为"{}",这个空对象就是exports,因为没有写exportsexports就默认指向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); 
        console.log(this.name); 
    }
};
person.speak();

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

小结:箭头函数本身没有this。在上面的demo中根据词法作用域,于是向上查找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

箭头函数的优点

  • 使用箭头函数比普通函数少些动词,如:functionreturn
  • this提前定义,从上下文可以捕获this

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

猜你喜欢

转载自blog.csdn.net/margin_0px/article/details/83583100