首页 文章

JavaScript中“=>”(由等于和大于等于的箭头形成)的含义是什么?

提问于
浏览
345

我知道 >= 运算符意味着大于或等于,但我在某些源代码中看到了 => . 那个运营商的意义是什么?

这是代码:

promiseTargetFile(fpParams, aSkipPrompt, relatedURI).then(aDialogAccepted => {
    if (!aDialogAccepted)
        return;

    saveAsType = fpParams.saveAsType;
    file = fpParams.file;

    continueSave();
}).then(null, Components.utils.reportError);

10 回答

  • 57

    正如其他人所说,这是一种创建函数的新语法 .

    但是,这种功能与正常功能不同:

    • 它们绑定 this 值 . 正如the spec所解释的那样,

    ArrowFunction不为arguments,super,this或new.target定义本地绑定 . 对ArrowFunction中的arguments,super,this或new.target的任何引用都必须解析为词法封闭环境中的绑定 . 通常,这将是立即封闭功能的功能环境 . 即使ArrowFunction可能包含对super的引用,步骤4中创建的函数对象也不会通过执行MakeMethod而成为方法 . 引用super的ArrowFunction总是包含在非ArrowFunction中,并且可以通过ArrowFunction的函数对象捕获的作用域访问实现super的必要状态 .

    • 他们是非构造者 .

    这意味着它们没有[[Construct]]内部方法,因此无法实例化,例如

    var f = a => a;
    f(123);  // 123
    new f(); // TypeError: f is not a constructor
    
  • 2

    它是什么

    This is an arrow function. 箭头函数是由ECMAscript 6引入的一种简短语法,可以与使用函数表达式的方式类似地使用 . 换句话说,您通常可以使用它们代替 function (foo) {...} 这样的表达式 . 但他们有一些重要的区别 . 例如,它们不绑定自己的 this 值(请参阅下面的讨论) .

    Arrow函数是ECMAscript 6规范的一部分,但不是今天大多数浏览器中使用的"normal" JavaScript的一部分 . 然而,它们在许多浏览器中都是partially supported in Node v. 4.0+(见下文) .

    You can read more in the Mozilla documentation on arrow functions .

    从Mozilla文档:

    与函数表达式相比,箭头函数表达式(也称为胖箭头函数)具有更短的语法,并且词汇绑定此值(不绑定它自己的this,arguments,super或new.target) . 箭头功能始终是匿名的 . 这些函数表达式最适合非方法函数,不能用作构造函数 .

    关于箭头函数的工作原理的注释

    箭头功能最方便的功能之一埋在上面的文本中:

    箭头函数...词法绑定此值(不绑定它自己的...)

    简单来说,这意味着箭头函数从其上下文中保留 this 值,并且没有自己的 this . 传统函数确实绑定了自己的 this 值,需要很多体操如 self = this; 等来从另一个函数中的一个函数访问或操纵 this . 有关此主题的更多信息,请参阅the explanation and examples in the Mozilla documentation .

    示例代码

    示例(也来自文档):

    var a = [
      "We're up all night 'til the sun",
      "We're up all night to get some",
      "We're up all night for good fun",
      "We're up all night to get lucky"
    ];
    
    // These two assignments are equivalent:
    
    // Old-school:
    var a2 = a.map(function(s){ return s.length });
    
    // ECMAscript 6 using arrow functions
    var a3 = a.map( s => s.length );
    
    // both a2 and a3 will be equal to [31, 30, 31, 31]
    

    兼容性说明

    您可以在Node中使用箭头功能,但浏览器支持不稳定 .

    浏览器对此功能的支持已经有了相当大的改进,但对于大多数基于浏览器的用法来说仍然不够普及 . 截至2017年12月12日,当前版本支持:

    • Chrome(v.45)

    • Firefox(v.22)

    • 边缘(第12节)

    • 歌剧(第32节)

    • Android浏览器(v.47)

    • Opera Mobile(第33版)

    • 适用于Android的Chrome(第47版)

    • Firefox for Android(v.44)

    • Safari(v.10)

    • iOS Safari(v.10.2)

    • 三星互联网(第5版)

    • 百度浏览器(v.7.12)

    不支持:

    • IE(通过v.11)

    • Opera Mini(通过v.8.0)

    • 黑莓浏览器(通过第10节)

    • IE Mobile(通过v.11)

    • 适用于Android的UC浏览器(通过v.11.4)

    • QQ(通过v.1.2)

    您可以在CanIUse.com找到更多(和更多当前)信息(无联属关系) .

  • 423

    这被称为箭头功能,ECMAScript 2015 spec的一部分......

    var foo = ['a', 'ab', 'abc'];
    
    var bar = foo.map(f => f.length);
    
    console.log(bar); // 1,2,3
    

    语法比上一个更短:

    // < ES6:
    var foo = ['a', 'ab', 'abc'];
    
    var bar = foo.map(function (f) {
      return f.length;
    });
    console.log(bar); // 1,2,3
    

    DEMO

    另一个很棒的东西是词汇 this ...通常,你会做类似的事情:

    function Foo() {
        this.name = name;
        this.count = 0;
        this.startCounting();
    }
    
    Foo.prototype.startCounting = function() {
      var self = this;
      setInterval(function () {
        // this is the Window, not Foo {}, as you might expect
        console.log(this); // [object Window]
        // that's why we reassign this to self before setInterval()
        console.log(self.count);
        self.count++;
      },1000)
    }
    
    new Foo();
    

    但是可以用这样的箭头重写:

    function Foo() {
        this.name = name;
        this.count = 0;
        this.startCounting();
    }
    
    Foo.prototype.startCounting = function() {
      setInterval(() => {        
        console.log(this); // [object Object]
        console.log(this.count); // 1, 2, 3
        this.count++;
      },1000)
    }
    
    new Foo();
    

    DEMO

    MDN
    More on Syntax

    有关更多信息,here's是何时使用箭头功能的一个很好的答案 .

  • 13

    我读过,这是 Arrow FunctionsArrow Functions 的象征

    这个

    var a2 = a.map(function(s){ return s.length });
    

    使用 Arrow Function 可以写成

    var a3 = a.map( s => s.length );
    

    MDN Docs

  • 6

    只是为了添加一个lambda可以在不使用map的情况下做的另一个例子:

    a = 10
    b = 2
    
    var mixed = (a,b) => a * b; 
    // OR
    var mixed = (a,b) => { (any logic); return a * b };
    
    console.log(mixed(a,b)) 
    // 20
    
  • 18

    使用Arrowfunction添加简单的CRUD示例

    //Arrow Function
     var customers   = [
       {
         name: 'Dave',
         contact:'9192631770'
       },
       {
         name: 'Sarah',
         contact:'9192631770'
       },
       {
         name: 'Akhil',
         contact:'9928462656' 
       }],
    
    // No Param READ
     getFirstCustomer = () => { 
       console.log(this);
       return customers[0];
     };
      console.log("First Customer "+JSON.stringify(getFirstCustomer())); // 'Dave' 
    
       //1 Param SEARCH
      getNthCustomer = index=>{
        if( index>customers.length)
        {
         return  "No such thing";
       }
       else{
           return customers[index];
         } 
      };
      console.log("Nth Customer is " +JSON.stringify(getNthCustomer(1))); 
    
       //2params ADD
      addCustomer = (name, contact)=> customers.push({
         'name': name,
         'contact':contact
        });
      addCustomer('Hitesh','8888813275');
      console.log("Added Customer "+JSON.stringify(customers)); 
    
      //2 param UPDATE
      updateCustomerName = (index, newName)=>{customers[index].name= newName};
      updateCustomerName(customers.length-1,"HiteshSahu");
      console.log("Updated Customer "+JSON.stringify(customers));
    
      //1 param DELETE
      removeCustomer = (customerToRemove) => customers.pop(customerToRemove);
      removeCustomer(getFirstCustomer());
      console.log("Removed Customer "+JSON.stringify(customers));
    
  • 8

    正如所有其他答案已经说过的那样,'s part of ES2015 arrow function syntax. More specifically, it'不是运算符,它是一个将参数与正文分开的标点符号: ArrowFunction : ArrowParameters => ConciseBody . 例如 . (params) => { /* body */ } .

  • 0

    这将是ECMAScript 6中引入的“箭头函数表达式” .

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/arrow_functions

    出于历史目的(如果Wiki页面稍后更改),它是:

    一支箭与函数表达式相比,函数表达式具有更短的语法,并且词汇绑定此值 . 箭头功能始终是匿名的 .

  • 20

    这些是箭头功能

    又称 Fat Arrow Functions . 它们是编写函数表达式的简洁方法,例如 function() {} .

    箭头函数在定义函数时可以不需要 functionreturn{} . 它们是单行的,类似于Java或Python中的Lambda表达式 .

    没有参数的示例

    var queue        = ['Dave', 'Sarah', 'Sharon'],
        nextCustomer = () => queue[0];
    
    console.log(nextCustomer()); // 'Dave'
    

    如果需要在同一个箭头函数中进行多个语句,则需要在此示例中将 queue[0] 包装在curley括号 {} 中 . 在这种情况下,不能省略return语句 .

    带有1个参数的示例

    var queue       = ['Dave', 'Sarah', 'Sharon'],
        addCustomer = name => { queue.push(name) }
    
    addCustomer('Toby');
    
    console.log(queue); // ['Dave', 'Sarah', 'Sharon', 'Toby']
    

    您可以从上面省略 {} .

    当存在单个参数时,可以省略参数周围的括号 () .

    具有多个参数的示例

    var addition = (x, y) => x + y
    
    console.log(addition(1, 5)); // 6
    

    一个有用的例子

    var fruits = [
        {name: 'Apple', price: 2},
        {name: 'Bananna', price: 3},
        {name: 'Pear', price: 1}
    ];
    

    如果我们想在单个阵列中获得每种水果的价格,在ES5中我们可以做到:

    fruits.map(function(fruit) {
        return fruit.price;
    }); // [2, 3, 1]
    

    在带有新箭头功能的ES6中,我们可以使这更简洁:

    fruits.map(fruit => fruit.price); // [2, 3, 1]
    

    有关箭头功能的更多信息,请参见here .

    浏览器兼容性

    • IE:尚不支持

    • 边缘:12(所有版本)

    • Firefox:22

    • Chrome:45

    • Safari:10

    • iOS Safari:10.2

    • Android浏览器:56

    可以在浏览器兼容性上找到其他最新信息here

  • 22

    ES6箭头功能:

    在javascript中, => 是箭头函数表达式的符号 . 箭头函数表达式没有自己的 this 绑定,因此不能用作构造函数 . 例如:

    var words = 'hi from outside object';
    
    let obj = {
      words: 'hi from inside object',
      talk1: () => {console.log(this.words)},
      talk2: function () {console.log(this.words)}
    }
    
    obj.talk1();  // doesn't have its own this binding, this === window
    obj.talk2();  // does have its own this binding, this is obj
    

    使用箭头功能的规则:

    • 如果有一个参数 exactly ,您可以省略参数的括号 .

    • 如果返回表达式并在同一行上执行此操作,则可以省略 {}return 语句

    For example:

    let times2 = val => val * 2;  
    // It is on the same line and returns an expression therefore the {} are ommited and the expression returns implictly
    // there also is only one argument, therefore the parentheses around the argument are omitted
    
    console.log(times2(3));
    

相关问题