iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
Modern Web

JavaScript學習日記系列 第 7

JavaScript學習日記 : Day7 - 函數(二)

ES6出現的Arrow function,看起來簡短許多,但卻充滿許多陷阱(限制),所以充份了解箭頭函數後,再往後使用上也會減少一些Bug,或是fix bug也會比較有頭緒。

1. 簡短的語法

// 一般表達式寫法
let buySomething = function(something) {
    return `我買了${something}`;
} 

// 箭頭函式
let buySomething = (something) => {
    return `我買了${something}`;
}

// 箭頭函式省略return
let buySomething = (something) => `我買了${something}`;

// 只有一個參數可升略括號
let buySomething = something => `我買了${something}`;

// 沒有參數時,一定要有括號
let buySomething = () => '我買了一些物品';

2. 箭頭函式沒有arguments

let randomParamFunc = () => {
    console.log(arguments);
}

randomParamFunc(1,2,3,4,5)

// arguments is not defined

3. 綁定的this不同

  • 一般函數 --- 呼叫的位置而定
  • 箭頭函數 --- 根據箭頭函數定義時,所處的執行環境而定,this會指向父作用域的this。

一般函數的例子:

let user = {
    id:123,
    name:"Gino",
    height:180,
    getHeight() {
        return this.height
    }
};

console.log(user.getHeight()) // 180

let getHeight = user.getHeight
console.log(getHeight()) // undefined

箭頭函數的例子:

function test() {
    return a => {
        console.log(this.a) // this會繼承test function的this
    }
}

let objA = {
    a:100
}

let objB = {
    b:200
}

let test1 = test.call(objA);
test1.call(objB); // 100

test函數內部的箭頭函數會補捉呼叫test函數時的this,所以會補捉到this綁定到objA,綁定後就無法再變更了,所以最後一行所顯示出的是100而不是200,另外也可以發現在箭頭函數中,是沒辦法使用apply、call、bind去指定this的指向。

4. 無法使用建構式

const makeCar = (brand, modal, color) => {
    this.brand = brand;
    this.modal = modal;
    this.color = color
}

const toyotaCar = new makeCar('Toyota','RAV4','white') //makeCar is not a constructor

5. DOM事件監聽

針對DOM事件監聽的函數中,this會指向全域(window),導致無法正常運作。

let targets = document.getElementsByTagName('div');
let changeColor = () => {
    this.style.color = 'blue' // this指向window
}

for(let i = 0; i < targets.length; i++) {
    targets[i].addEventListener('click',changeColor)
}

6. Prototype中使用this

在prototype中新增方法如果有用到this,並不會如意的指向呼叫的object,而是會指向全域(window)。

function MakeCar(brand, modal, color){
    this.brand = brand;
    this.modal = modal;
    this.color = color
}

MakeCar.prototype.carInfo = () => {
    console.log(`這是一台${this.brand},型號為${this.modal}的${this.color}色汽車`)
}

const car = new MakeCar('Toyota','RAV4','white');

car.carInfo(); // 這是一台undefined,型號為undefined的undefined色汽車

參考文章:

鐵人賽:箭頭函式 (Arrow functions)

當ES6箭頭函式遇上this


上一篇
JavaScript學習日記 : Day6 - 函數(一)
下一篇
JavaScript學習日記 : Day8 - 作用域(Scope)
系列文
JavaScript學習日記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言