zoukankan      html  css  js  c++  java
  • 箭头函数

    1、箭头函数介绍

    //ES6
    let fn=v=>v; console.log(fn("好酷的箭头函数!"));//好酷的箭头函数!
    //ES5
    let fn=function(v){ return v; } console.log(fn("好酷的箭头函数!"));//好酷的箭头函数!

     2、写法

     如果只有一条语句,可以将{}和return省略掉

    v=>v+v;
    //相当于
    function (v){.
        return v+v;
    }
    

     如果语句为多条,则不可以省略{}和return

    v=>{
        var sum=0;
        for(let i=0;i<v;i++){
            sum+=i;
        }
        return sum;
    }
    

     当没有参数或有多个参数时,需要用括号()括起来:

    (num1,num2)=>num1+num2;
    

     当省略{}和return时,如果返回的内容是一个对象,对象需要用括号()括起来

    ()=>({name:"laoliu"});
    

     箭头函数不能用于构造函数

    //正常情况
    var Box=function(age){
        this.myAge=age;
    }
    var obj=new Box(20);
    console.log(obj.myAge);//20
    
    //箭头函数
    var Box=age=>{
        this.myAge=age;
    }
    var obj=new Box(20);//Box is not a constructor
    console.log(obj.myAge);
    

     箭头函数没有prototype属性

    var Foo = () => {};
    console.log(Foo.prototype); // undefined
    

     箭头函数不绑定arguments

    var arguments = 42;
    var fn = () => arguments;
    console.log(fn()); // 42
    function foo() {
    var f = (i) => arguments[0]+i;
    return f(2);
    }
    console.log(foo(1)); // 3
    

     箭头函数不绑定this

    window.color = "red";
    //let 声明的全局变量不具有全局属性,即不能用window.访问
    let color = "green";
    let obj = {
    color: "blue",
    getColor: () => {
    return this.color;//this指向window
    }
    };
    let sayColor = () => {
    return this.color;//this指向window
    };
    obj.getColor();//red
    sayColor();//red
    

     箭头函数无法使用 call()或 apply()来改变其运行的作用域

    window.color = "red";
    let color = "green";
    let obj = {
      color: "blue"
    };
    let sayColor = () => {
      return this.color;
    };
    sayColor.apply(obj);//red
    

    参考文献:https://blog.csdn.net/u012149969/article/details/80261081

  • 相关阅读:
    Awstats显示国家地区插件GeoIP安装 枯木
    springboot_shiro与shiro.ini文件
    Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
    mybatis的dao层xml
    springboot的配置文件
    万事无忧之用泡MM的方式演绎设计模式
    C#设计模式
    软件架构
    什么时候应该使用Web Service
    Spring框架快速入门之简介
  • 原文地址:https://www.cnblogs.com/sun-web/p/10729582.html
Copyright © 2011-2022 走看看