1. 程式人生 > >ECMAScript6箭頭函數ArrowFunction"=>"

ECMAScript6箭頭函數ArrowFunction"=>"

ecmascript javascript 箭頭函數

一、說明

ECMAScript6可以用箭頭"=>"定義函數。x => x * x(x) => {return x * x;}與匿名函數function(x){return x * x;}相等。

二、示例

2.1 沒有參數的箭頭函數

var f = () => 9;
console.log(f()); //9

2.2 一個參數的箭頭函數

var f = x => x * x;
console.log(f(3)); //9
var f = x => {return x * x;};
console.log(f(3)); //9
var f = (x) => x * x;
console.log(f(3)); //9
var f = (x) => {return x * x;};
console.log(f(3)); //9

2.3 兩個或更多參數的箭頭函數

var f = (x, y) => x * y;
console.log(f(2, 3)); //6
var f = (x, y , ...more) => {
    var multiply = x * y;
    for(var i = 0; i < more.length; i++){
        multiply *= more[i];
    }
    return multiply;
};
console.log(f(2, 3, 4, 5)); //120

2.4 map/reduce應用

var f = [1, 2, 3].map(x => x * x);
console.log(f); //[1, 4, 9]
var f = [1, 2, 3].reduce((x, y) => x + y);
console.log(f); //6

三、this作用域/返回對象

3.1 this作用域

箭頭函數中的this總是指向外層作用域,即使在內層函數裏面,所以可以不用寫var that = this;

var obj = {
    name: ‘mazey‘,
    f: function(){
        var myName = () => this.name; //這裏的this指向obj
        return myName();
    }
};
console.log(obj.f()); //mazey

3.2 返回對象

因為對象和塊的沖突問題,箭頭函數返回一個如{name:‘mazey‘}的對象必需用()括起來。

var f = () => {name:‘mazey‘};
console.log(f()); //undefined
var f = () => ({name:‘mazey‘});
console.log(f()); //{name: "mazey"}

四、練習代碼

<script>
var f = () => 9;
console.log(f()); //9
var f = x => x * x;
console.log(f(3)); //9
var f = x => {return x * x;};
console.log(f(3)); //9
var f = (x) => x * x;
console.log(f(3)); //9
var f = (x) => {return x * x;};
console.log(f(3)); //9
var f = (x, y) => x * y;
console.log(f(2, 3)); //6
var f = (x, y , ...more) => {
    var multiply = x * y;
    for(var i = 0; i < more.length; i++){
        multiply *= more[i];
    }
    return multiply;
};
console.log(f(2, 3, 4, 5)); //120
var f = [1, 2, 3].map(x => x * x);
console.log(f); //[1, 4, 9]
var f = [1, 2, 3].reduce((x, y) => x + y);
console.log(f); //6
var obj = {
    name: ‘mazey‘,
    f: function(){
        var myName = () => this.name; //這裏的this指向obj
        return myName();
    }
};
console.log(obj.f()); //mazey
var f = () => {name:‘mazey‘};
console.log(f()); //undefined
var f = () => ({name:‘mazey‘});
console.log(f()); //{name: "mazey"}
</script>

ECMAScript6箭頭函數ArrowFunction”=>”

本文出自 “不知不問” 博客,請務必保留此出處http://mazey.blog.51cto.com/12997993/1948391

ECMAScript6箭頭函數ArrowFunction"=>"