js 箭頭函數

來源:互聯網
上載者:User

標籤:一個   詞法   asc   new   結果   第一個   標準   get   java   

箭頭函數

ES6標準新增了一種新的函數: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;}

如果要返回一個對象:
// 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

由於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
 

js 箭頭函數

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.