• 箭头函数


    箭头函数这样写可以返回对象{ foo: x }:

    x => ({ foo: x })

     箭头函数内部的this是词法作用域,由上下文确定,即在定义的时候就确定了它得this指向,而不是在调用它的时候。箭头函数只会从自己的父作用域里继承this,和谁调用的没有关系:

    let a = {
      foo: 1,
      bar: () => console.log(this.foo)   // 此时的this指向Window
    }
    
    a.bar()  // undefined
    function A() {
      this.foo = 1
    }
    
    A.prototype.bar = () => console.log(this.foo)   // 此时this指向Window
    
    let a = new A()
    a.bar()  //undefined

    通过call()、apply()或bind()方法调用一个箭头函数时,只能传递参数,不能绑定this,他们的第一个参数会被忽略。

    箭头函数不绑定arguments:

    var a= (c, d) => {
        console.log(arguments)
    }
    a(1,2)   // Uncaught ReferenceError: arguments is not defined

    可以用剩余参数获得传过来的不定数量的参数:

    var a= (...v) => {
        console.log(v)
    }
    a(1,2)   // [1, 2]

    普通函数都有prototype属性,但是箭头函数没有prototype属性。

    箭头函数不能用作构造器,和 new一起用会抛出错误。

    var Foo = () => {};
    var foo = new Foo(); // TypeError: Foo is not a constructor

    虽然箭头函数中的箭头不是运算符,但箭头函数具有与常规函数不同的特殊运算符优先级解析规则:

    let callback;
    callback = callback || function() {}; // ok
    callback = callback || () => {};      // SyntaxError: invalid arrow-function arguments
    callback = callback || (() => {});    // ok

    箭头函数不能作为Generator函数,不能使用yield关键字。

    箭头函数在ES6的class中声明的方法为当前实例方法,不是该实例上原型的方法:

    //deom1
    class Super{
        sayName(){
            //do some thing here
        }
    }
    //通过Super.prototype可以访问到sayName方法,这种形式定义的方法,都是定义在prototype上
    var a = new Super()
    var b = new Super()
    a.sayName === b.sayName //true  所有实例化之后的对象共享prototypy上的sayName方法
    
    
    //demo2
    class Super{
        sayName =()=>{
            //do some thing here
        }
    }
    //通过Super.prototype访问不到sayName方法,该方法没有定义在prototype上
    var a = new Super()
    var b = new Super()
    a.sayName === b.sayName //false  实例化之后的对象各自拥有自己的sayName方法,a的sayName和b的sayName拥有不同的内存空间,他们的引用地址不一样。
  • 相关阅读:
    Abp通用配置模块的设计
    Windbg分析高内存占用问题
    IdentityServer4 知多少
    找不到对象,『空对象模式』来帮忙
    EF Core中避免贫血模型的三种行之有效的方法(翻译)
    Razor Page Library:开发独立通用RPL(内嵌wwwroot资源文件夹)
    .NET Core 源码导航(按程序集链接)
    ASP.NET Core Web App应用第三方Bootstrap模板
    给ASP.NET Core Web发布包做减法
    Azure Web连接到Azure MySql Db
  • 原文地址:https://www.cnblogs.com/xjy20170907/p/11424196.html
Copyright © 2020-2023  润新知