=> 箭頭函數 · 方便、快捷,也要小心坑
箭頭函數是必須要掌握的,今天我們一起來學習一下,它給開發(fā)者帶來方便的同時,也要留意它的「無能」。先看一個例子:
- const names = [
- 'wsy',
- 'suyan',
- '前端小課'
- ];
- let lengths = names.map(name => name.length);
- console.log('lengths = ', lengths);
結果如圖:
先看下它的語法:
1. 無參數
- function call(callback) {
- callback();
- }
- call(() => {
- console.log('arrow void');
- });
- // 箭頭函數類似于下面這個函數
- call(function () {
- console.log('void');
- });
2. 只有一個參數,無返回值
- function call(callback) {
- callback('前端小課');
- }
- call(name => {
- console.log('arrow', name);
- });
- // 箭頭函數類似于下面這個函數
- call(function (name) {
- console.log(name);
- });
3. 只有一個參數,有返回值
- function call(callback) {
- // 返回值為 4
- let len = callback('前端小課');
- console.log(len);
- }
- // 只有一行表達式省略大括號
- call(name => name.length);
- // 類似于這個
- call(name => {
- return name.length;
- });
- // 箭頭函數類似于下面這個函數
- call(function (name) {
- return name.length;
- });
4.有多個參數,有返回值
- function call(callback) {
- let len = callback(1, 2, 3);
- console.log(len); // 6
- }
- // 多個個參數,有返回值,只有一行表達式省略大括號
- call((a, b, c) => a + b + c);
- // 類似與這個
- call((a, b, c) => {
- return a + b + c;
- });
- // 箭頭函數類似于下面這個函數
- call(function (a, b, c) {
- return a + b + c;
- });
從上面這些例子可以知道,每個箭頭函數都能寫出一個與其功能相同的普通函數,那為什么還用箭頭函數?
在 連接你、我、他 —— this 這節(jié)課程中使用箭頭函數解決了 this 指向的問題。不知道你們有沒有發(fā)現(xiàn)當寫下面這兩個函數的時候,VSCode 默認使用的是箭頭函數:
- setTimeout(() => {
- // 這里是箭頭函數
- }, 100);
- setInterval(() => {
- // 這個是箭頭函數
- }, 200);
使用箭頭函數有幾點需要留意:
1. 讓函數更簡短,上面例 3 就是一個很好的例子;
2. 沒有自己的 this 和 argument,比如有如下代碼:
- let person = {
- name: 'suyan',
- showName: function (age) {
- window.setTimeout(() => {
- console.log('this = ', this);
- console.log('arguments = ', arguments);
- console.log(this.name, age);
- }, 100);
- }
- };
- person.showName(20);
打印結果為:
3. 不能作為構造函數;
- let Dog = name => {
- this.name = name;
- };
- // 錯誤 Uncaught TypeError: Dog is not a constructor
- let aDog = new Dog('fe');
- let Dog2 = function (name) {
- this.name = name;
- };
- // 正確
- let aDog2 = new Dog2('fe');
4. 箭頭函數沒有 prototype 屬性:
- let Dog = name => {
- this.name = name;
- };
- Dog.prototype; // undefined
5.不能通過 call、apply 綁定 this
- var name = 'I am widow';
- let animal = {
- name: 'animal',
- showName: age => {
- console.log('this = ', this);
- console.log('name | age = ', this.name, age);
- }
- };
- let dog = {
- name: 'dog'
- };
- animal.showName.call(dog, 20);
- animal.showName.apply(dog, [21]);
- let bindName = animal.showName.bind(dog, 22);
- bindName();
運行代碼,結果如下:
由于箭頭函數沒有 this 指針,不能通過 call、apply、bind 的方式來修改 this。只能傳遞參數,this 參數將被忽略。