ES6-箭头函数

2018-05-28  本文已影响0人  闪电西兰花
//原始写法
const number = [2,4,6];
const double = number.map(function(number){
    return number * 2;
})
console.log(double);       //[4, 8, 12]
//箭头函数写法
//没有参数时,直接()=>{}
//有一个参数时,如下,等同于(number)=>{}
//有多个参数时,用逗号隔开即可,(number,i)=>{}
const number = [2,4,6];
const double = number.map(number => {    
    return number * 2;
})
console.log(double);       //[4, 8, 12]
//箭头函数隐示返回
//因为箭头函数是匿名函数,因此通常将其赋值给一个变量
const number = [2,4,6];
const double = number.map(number => number * 2);
console.log(double);       //[4, 8, 12]
const Asher = {
    name: 'Asher',
    hobbies: ['Coding','Sleeping','Reading'],
    printHobbies: function(){
        console.log(this);        //this在运行过程中动态指定,指向调用该函数的Asher对象
        this.hobbies.map(function(hobby){
            console.log(this);    //window对象,因为这里没有作为对象的方法被调用,也没有使用call,apply等改变this值(严格模式下指向undefined)
            console.log( this.name + hobby );
        })
    }
}
Asher.printHobbies();   //Coding,Sleeping,Reading

//改进后的写法
const Asher = {
    name: 'Asher',
    hobbies: ['Coding','Sleeping','Reading'],
    printHobbies: function(){
        var _this = this;        //提前将this保存起来
        this.hobbies.map(function(hobby){
            console.log( _this.name + hobby );
        })
    }
}
Asher.printHobbies();   //AsherCoding,AsherSleeping,AsherReading

//改为箭头函数
//箭头函数中的this继承自父作用域,定义的时候就被指定了并且也不会随着调用而改变
const Asher = {
    name: 'Asher',
    hobbies: ['Coding','Sleeping','Reading'],
    printHobbies: function(){
        this.hobbies.map(hobby=>{
            console.log( this.name + hobby );
        })
    }
}
Asher.printHobbies();   //AsherCoding,AsherSleeping,AsherReading
function multiply(a,b){
    a = a || 3;
    b = b || 5;
    console.log( a * b );
}
multiply(2,2);         //4
multiply();           //15,不传参的情况下函数会默认给参数赋值undefined

//ES6写法
function multiply(a = 3,b = 5){
    console.log( a * b );
}
multiply(2,2);         //4
multiply();           //15
multiply(2);           //10
multiply(undefined,8);    //24
//1.作为构造函数,一个对象需要绑定方法
const Person = (name,points)=>{
    this.name = name;
    this.points = points;
}
const Asher = new Person('Asher',5);   //Person is not a constructor,箭头函数不存在this绑定

const Person = function(name,points){
    this.name = name;
    this.points = points;
}
const Asher = new Person('Asher',5);   
Person.prototype.addPoints = () => {
    console.log(this);    //window,这里的this按理继承自父元素
    this.points ++;
    console.log(this.points);
}
Asher.addPoints();        //NaN

//正确写法
const Person = function(name,points){            //构造函数
    this.name = name;
    this.points = points;
}
const Asher = new Person('Asher',5);   
Person.prototype.addPoints = function(){
    this.points ++;
    console.log(this.points);
}
Asher.addPoints();        //6
//2.需要用this的时候
//3.需要用到arguments对象的时候
上一篇下一篇

猜你喜欢

热点阅读