1. 程式人生 > 實用技巧 >JS_0024:箭頭函式()=>{} 的使用方式

JS_0024:箭頭函式()=>{} 的使用方式

1,

document.querySelector('#openCamera').addEventListener('click', function () {
    const videoSelect = document.querySelector('#videoDevice');
    webAR.listCamera(videoSelect)
        .then(msg => {
            // 隱藏"開啟攝像頭"按鈕
            this.style.display = 'none';
            videoSelect.style.display 
= 'inline-block'; document.querySelector('#start').style.display = 'inline-block'; document.querySelector('#stop').style.display = 'inline-block'; videoSelect.onchange = () => { webAR.openCamera(JSON.parse(videoSelect.value)); };
// 開啟攝像頭 // 開啟後置攝像頭引數: {audio: false, video: {facingMode: {exact: 'environment'}}} webAR.openCamera(JSON.parse(videoSelect.value)) .then(msg => { console.info(msg); }).catch(err => { console.info(err); }); }) .
catch(err => { // 沒有找到攝像頭 console.info(err); }); }); // 開啟識別 document.querySelector('#start').addEventListener('click', () => { webAR.startRecognize((msg) => { console.info(msg); alert('識別成功'); }); }, false); // 暫停識別 document.querySelector('#stop').addEventListener('click', () => { webAR.stopRecognize(); }, false);

2,

js(=>) 箭頭函式
ES6標準新增了一種新的函式:Arrow Function(箭頭函式)。

為什麼叫Arrow Function?因為它的定義用的就是一個箭頭:

x => x * x
上面的箭頭函式相當於:

function (x) {
    return x * x;
}
箭頭函式相當於匿名函式,並且簡化了函式定義。箭頭函式有兩種格式,一種像上面的,只包含一個表示式,連{ ... }和return都省略掉了。還有一種可以包含多條語句,這時候就不能省略{ ... }和return:

複製程式碼
複製程式碼
x => {
    if (x > 0) {
        return x * x;
    }
    else {
        return - x * x;
    }
}
複製程式碼
複製程式碼
如果引數不是一個,就需要用括號()括起來:

複製程式碼
複製程式碼
// 兩個引數:
(x, y) => x * x + y * y

// 無引數:
() => 3.14

// 可變引數:
(x, y, ...rest) => {
    var i, sum = x + y;
    for (i=0; i<rest.length; i++) {
        sum += rest[i];
    }
    return sum;
}
複製程式碼
複製程式碼
如果要返回一個物件,就要注意,如果是單表示式,這麼寫的話會報錯:

// SyntaxError:
x => { foo: x }
因為和函式體的{ ... }有語法衝突,所以要改為:
// ok:
x => ({ foo: x })
this
箭頭函式看上去是匿名函式的一種簡寫,但實際上,箭頭函式和匿名函式有個明顯的區別:箭頭函式內部的this是詞法作用域,由上下文確定。

回顧前面的例子,由於JavaScript函式對this繫結的錯誤處理,下面的例子無法得到預期結果:

複製程式碼
複製程式碼
var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = function () {
            return new Date().getFullYear() - this.birth; // this指向window或undefined
        };
        return fn();
    }
};
複製程式碼
複製程式碼
現在,箭頭函式完全修復了this的指向,this總是指向詞法作用域,也就是外層呼叫者obj:

複製程式碼
複製程式碼
var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = () => new Date().getFullYear() - this.birth; // this指向obj物件
        return fn();
    }
};
obj.getAge(); // 25
複製程式碼
複製程式碼
如果使用箭頭函式,以前的那種hack寫法:

var that = this;
就不再需要了。

由於this在箭頭函式中已經按照詞法作用域綁定了,所以,用call()或者apply()呼叫箭頭函式時,無法對this進行繫結,即傳入的第一個引數被忽略:

複製程式碼
複製程式碼
var obj = {
    birth: 1990,
    getAge: function (year) {
        var b = this.birth; // 1990
        var fn = (y) => y - this.birth; // this.birth仍是1990
        return fn.call({birth:2000}, year);
    }
};
obj.getAge(2015); // 25