ES6 - 箭头函数

2019-10-08  本文已影响0人  ElricTang

箭头函数有点类似于匿名函数,而且更加简洁。

一. 语法:
function add(x,y){
    return x + y;
}
console.log(add(1,2));// 3
let add = (x,y) =>{
    return x + y;
};
console.log(add(1,2));// 3
let add = (x,y) => x + y ;
console.log(add(1,2));// 3
let arr = [1,3,4].map(e => {
    return e + 1;
})
console.log(arr);// [ 2, 4, 5 ]
setTimeout(()=>{
    console.log('无参数')
},500);// 无参数
let show = ({name,age}) => ({name:name,age:age});
console.log(show({name:'tom',age:21}));// { name: 'tom', age: 21 }
let test1 = ([a,b,c]) => {
    return a + b + c;
}

let test2 = ({name,age,hobby}) => {
    return `my name is ${name} , i am ${age} years old , hobby is ${hobby}`;
}

console.log(test1([1,2,3]));// 6
console.log(test2({name:'tom',age:21,hobby:'game'}));
// my name is tom , i am 21 years old , hobby is game
二. 主要特点:
var Foo = () => {};
let foo = new Foo();// TypeError: Foo is not a constructor
function Person(name){
    this.name = name;
    this.say = function(){
        return function(){
            console.log(this.name);
        }       
    }
}
let person = new Person('tom');
person.say()();// undefined

由于this绑定问题(函数创建了自己的this),得不到期望结果

function Person(name){
    this.name = name;
    this.say = function(){
        let that = this;
        return function(){
            console.log(that.name);
        }       
    }
}
let person = new Person('tom');
person.say()();// tom

在没有箭头函数之前,我们经常使用中间量来保存this的引用。成功的解决了this的问题,但是不够优雅。

function Person(name){
    this.name = name;
    this.say = function(){
        return ()=>{
            console.log(this.name);
        }       
    }
}
let person = new Person('tom');
person.say()();// tom

因为箭头函数没有绑定this,它的this是通过作用域寻找上一层的this,效果与上面的一样。

let obj = {
    base:1,
    addWithCall:function(x){
        let fn = function(){
            return x + this.base;
        }
        let b = {
            base:10
        };
        return fn.call(b,x); 
    }
}
console.log(obj.addWithCall(1));// 11

使用箭头函数,箭头函数内部的this是词法作用域,由上下文确定。也就是说this.base指向的是obj的base

let obj = {
    base:1,
    addWithCall:function(x){
        let fn = () => x + this.base;
        let b = {
            base:10
        };
        return fn.call(b,x); 
    }
}
console.log(obj.addWithCall(1));// 2
// 例子1:
let arguments = [1,2,3];

let a = () => arguments[0];

console.log(a(9));// 1
// 例子2:
function b(){
    return () => {
        return arguments[0];
    }
}

console.log(b(1)(2));// 1

解决方案:使用剩余参数代替arguments

function b(){
    return (...args) => {
        return args[0];
    }
}

console.log(b(1)(2));// 2
var Foo = () => {};
console.log(Foo.prototype); // undefined
上一篇下一篇

猜你喜欢

热点阅读