關於es6的箭頭函數使用與內部this指向


特型介紹:箭頭函數是ES6新增的特性之一,它為JS這門語言提供了一種全新的書寫函數的語法。

'use strcit';
let arr = [1,2,3];
//ES5
let es5 = arr.map(function(n){
    return n*2;
});
//ES6
let es6 = arr.map(n => n*2);
console.log(es5);    //[2,4,6]
console.log(es6);    //[2,4,6]

箭頭函數簡化了原先的函數語法,不需要再寫 function ,如果函數體只有一行代碼的話連 return 都不用寫,這個特性對於熱衷於簡化流程和工作的程序員來說相當對胃口。

箭頭函數支持兩種模式的函數體寫法,我們姑且叫他簡潔函數體和塊級函數體。

'use strcit';
// 簡潔函數體
let fn = x => x * x;

// 塊級函數體
let fn = (x, y) => {return x + y;};

簡介函數體默認會把表達式的結果返回,塊級函數體需要手動 return 。如果想要返回一個對象又想使用簡潔函數體的話,需要這么寫:

'use strcit';
let fn = () => ({});
fn();   // {}

 如果寫成 var fn = () => {} ,那么執行 fn() 只能返回 undefined 。

'use strict';
//第一種
let Person = function(){
    this.age = 2;
    let that = this;
    setTimeout(function(){
     that.age++;
        console.log(that.age);
    },1000);
};

//第二種
let Person = function(){
    this.age = 2;
    setTimeout(function(){
     this.age++;
        console.log(this.age);
    }.bind(this),1000);
};
new Person();

之前我們想操作setTimeout參數function內部的this可能會用上述兩種方法,看上去不錯了, 但是現在有了箭頭函數就不一樣了,代碼如下:

'use strict';
let Person = function(){
    this.age = 2;
    setTimeout(() => {
     this.age++;
        console.log(this.age);
    },1000);
};
new Person();  

由於箭頭函數已經綁定了this 的值,即使使用apply或者call也不能只能起到傳參數的作用,並不能強行改變箭頭函數里的this。

'use strict';
let obj = {
    x:1,
    show1:function(y){
        let fn = y => y+this.x;
        return fn(y);
    },
    show2:function(y){
        let fn = v => v + this.x;
        let whatever = {
            x: 2
        };
        return fn.call(whatever, y);
    }
};
console.log(obj.show1(1));    //2
console.log(obj.show2(2));    //3

箭頭函數不能與new 關鍵字一起使用,會報錯

'use strict';
let Fn = () => {
    this.a = 1;
};
let f = new Fn();    // Error


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM