ES6新特性箭头函数ArrowFunction => 案例教程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_18895975/article/details/90176824

ES6新特性箭头函数ArrowFunction => 案例教程


=> 是ES6中新加的匿名函数使用 基础语法 如下

var defFun= x=>x*x;//相当于 function(x){return x*x}
console.log(defFun(4));

箭头函数Return

箭头函数有两种格式, 一种只包含一个表达式,没有{…} 和 return 。 一种包含多条语句, 这个时候{} return 就不能省略

var defFun2= x=>{
    if (x%2==1){return "奇数";}else{return "偶数";}
}
console.log(defFun2(13));

传递多个参数

//()=>表示无参
var defFun3=(x,y)=>{
    return x+"+"+y+"和为"+(x+y);
}
console.log(defFun3(3,5));

返回对象1

var defFun4=(x,y)=>{return {"pram1":x,"pram2":y};}
console.log(defFun4(4,6).pram1,defFun4(4,6).pram2);

返回对象2

//官方推荐
var defFun5=(x,y)=>({"pram1":x,"pram2":y})
console.log(defFun5(5,7).pram1,defFun5(5,7).pram2);

箭头函数中的this作用域

箭头函数修复了this的指向,this 总是指向词法作用域,也就是外层调用者obj

var ManObj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = function () {
            return new Date().getFullYear()-this.birth; // this指向window或undefined
        };
        return "ManObj年龄"+fn();//NAN
    }
};
console.log(ManObj.getAge());
var WomanObj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = ()=> new Date().getFullYear() - this.birth; // this指向WomanObj对象
        return "WomanObj年龄"+fn();
    }
};
console.log(WomanObj.getAge());//2019-1990=29

箭头函数使用注意

箭头函数不能用作构造器,没有prototype属性 IE不支持 Edge支持

var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor
console.log(Foo.prototype); // undefined

箭头函数兼容性

在这里插入图片描述

参考地址

官方网站

猜你喜欢

转载自blog.csdn.net/qq_18895975/article/details/90176824