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

问题描述 投票:392回答:12

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

这是代码:

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

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

    continueSave();
}).then(null, Components.utils.reportError);
javascript syntax ecmascript-6 arrow-functions
12个回答
502
投票

What It Is

这是一个箭头功能。箭头函数是ECMAscript 6引入的一种简短语法,可以类似于使用函数表达式的方式使用。换句话说,您经常可以使用它们来代替像function (foo) {...}这样的表达式。但他们有一些重要的区别。例如,他们没有绑定自己的this值(请参阅下面的讨论)。

箭头功能是ECMAscript 6规范的一部分。它们尚未在所有浏览器中受支持,但它们部分或完全受支持in Node v. 4.0+以及自2018年起使用的大多数现代浏览器。(我在下面列出了支持浏览器的部分列表)。

You can read more in the Mozilla documentation on arrow functions

从Mozilla文档:

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

关于this如何在箭头函数中起作用的注记

箭头函数最方便的功能之一隐藏在上面的文本中:

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

这意味着简单来说,箭头函数保留了this值,并且没有自己的this。传统函数可以绑定自己的this值,具体取决于它的定义和调用方式。这可能需要许多体操,如self = this;等,从另一个功能内的一个功能访问或操纵this。有关此主题的更多信息,请参阅the explanation and examples in the Mozilla documentation

Example Code

示例(也来自文档):

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]

Notes on Compatibility

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

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

  • Chrome(v.45 +)
  • Firefox(v.22 +)
  • 边缘(v.12+)
  • 歌剧(32+)
  • Android浏览器(v.47 +)
  • Opera Mobile(v.33 +)
  • Chrome for Android(v.47 +)
  • Firefox for Android(v.44 +)
  • Safari(v.10+)
  • Safari病毒(b.10.2+)
  • 三星互联网(v.5+)
  • 百度浏览器(v.2.1)

不支持:

  • IE(通过第11节)
  • Opera Mini(通过v.8.0)
  • 黑莓浏览器(通过第10节)
  • IE Mobile(通过v.11)
  • 适用于Android的UC浏览器(通过v.11.4)
  • QQ(通过v.1.2)

您可以在CanIUse.com(无联盟)找到更多(和更新的)信息。


2
投票

正如所有其他答案已经说过的那样,它是ES2015箭头函数语法的一部分。更具体地说,它不是一个运算符,它是一个标点符号,用于将参数与正文分开:bind(this)。例如。 ArrowFunction : ArrowParameters => ConciseBody


1
投票

(params) => { /* body */ }箭头功能:

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

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{}语句

例如:

return

0
投票

用符号(=>)表示的箭头函数可以帮助您创建匿名函数和方法。这导致更短的语法。例如,下面是一个简单的“添加”功能,它返回两个数字的相加。

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));

通过使用“箭头”语法,上述功能变得更短,如下所示。

function Add(num1 , num2 ){ return num1 + num2; }

上面的代码有两部分,如上图所示: -

输入: - 此部分指定匿名函数的输入参数。

逻辑: - 此部分位于符号“=>”之后。本节具有实际功能的逻辑。

许多开发人员认为箭头函数使您的语法更短,更简单,从而使您的代码可读。

如果您相信上述句子,那么请允许我向您保证这是一个神话。如果你想一下,使用箭头符号在一行中创建的神秘函数可以读取具有名称的正确编写函数。

arrow函数的主要用途是确保代码在调用者上下文中运行。

请参阅下面的代码,其中定义了全局变量“context”,此全局变量在函数“SomeOtherMethod”中访问,该函数从其他方法“SomeMethod”调用。

这个“SomeMethod”具有本地“上下文”变量。现在因为“SomeOtherMethod”从“SomeMethod”调用,我们希望它显示“本地上下文”,但它显示“全局上下文”。

enter image description here

但如果使用箭头功能替换呼叫,它将显示“本地上下文”。

var context = “global context”;

function SomeOtherMethod(){
alert(this.context);
}

function SomeMethod(){
this.context = “local context”;
SomeOtherMethod();
}

var instance = new SomeMethod();

我鼓励你阅读这个链接(var context = "global context"; function SomeMethod(){ this.context = "local context"; SomeOtherMethod = () => { alert(this.context); } SomeOtherMethod(); } var instance = new SomeMethod(); ),它解释了javascript上下文的所有场景,以及在哪些场景中不调用调用者上下文。

您还可以看到Arrow function in JavaScript的演示,它实际上演示了Context这个术语。


68
投票

这被称为箭头功能,是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

另一个很棒的东西是lexical 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是何时使用箭头功能的一个很好的答案。


24
投票

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

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

出于历史目的(维基页面稍后更改),它是:

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


20
投票

只是为了添加一个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

19
投票

These are Arrow Functions

也称为Fat Arrow Functions。它们是编写函数表达式的简洁明了的方法,例如qazxsw poi。

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

没有参数的示例

{}

如果需要在同一个箭头函数中进行多个语句,则需要在curley括号const queue = ['Dave', 'Sarah', 'Sharon']; const nextCustomer = () => queue[0]; console.log(nextCustomer()); // 'Dave'中包装queue[0]。在这种情况下,不能省略return语句。

带1个参数的示例

{}

您可以从上面省略const queue = ['Dave', 'Sarah', 'Sharon']; const addCustomer = name => { queue.push(name); }; addCustomer('Toby'); console.log(queue); // ['Dave', 'Sarah', 'Sharon', 'Toby']

当存在单个参数时,可以省略参数周围的括号{}

具有多个参数的示例

()

一个有用的例子

const addNumbers = (x, y) => x + y

console.log(addNumbers(1, 5)); // 6

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

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

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

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

有关箭头功能的更多信息,请访问fruits.map(fruit => fruit.price); // [2, 3, 1]

浏览器兼容性

  • IE:不支持
  • 边缘:12+(所有版本)
  • Firefox:22+
  • Chrome:45+
  • Safari:10+
  • iOS Safari:10.2+
  • Android浏览器:56+

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


13
投票

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

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

  • 它们绑定了here值。正如this所解释的那样, ArrowFunction不为the specargumentssuperthis定义局部绑定。在ArrowFunction中对new.targetargumentssuperthis的任何引用必须在词汇封闭环境中解析为绑定。通常,这将是直接封闭函数的函数环境。 即使ArrowFunction可能包含对new.target的引用,步骤4中创建的函数对象也不会通过执行super而成为方法。引用MakeMethod的ArrowFunction总是包含在非ArrowFunction中,并且可以通过ArrowFunction的函数对象捕获的作用域访问实现super的必要状态。
  • 他们是非构造者。 这意味着它们没有[[Construct]]内部方法,因此无法实例化,例如 super

8
投票

我读过,这是var f = a => a; f(123); // 123 new f(); // TypeError: f is not a constructor Arrow Functions的象征

这个

ES6

使用var a2 = a.map(function(s){ return s.length }); 可以写成

Arrow Function

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


6
投票

使用箭头功能添加简单的CRUD示例

MDN Docs

3
投票

对其他答案不满意。截至2019年3月13日,最高投票回答是事实错误。

什么 //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)); 意味着简短的版本是写一个函数的快捷方式和绑定到当前的=>

this

实际上是一条捷径

const foo = a => a * 2;

你可以看到所有缩短的东西。我们不需要const foo = function(a) { return a * 2; }.bind(this); ,也不需要functionreturn,甚至不需要括号或括号

稍微长一点的箭头函数可能是

.bind(this)

显示如果我们想要函数的多个参数,我们需要括号,如果我们想要写一个以上的表达式,我们需要大括号和一个显式的const foo = (width, height) => { const area = width * height; return area; };

了解return部分非常重要,这是一个很大的话题。它与.bind在JavaScript中的含义有关。

所有函数都有一个名为this的隐式参数。调用函数时如何设置this取决于函数的调用方式。

采取

this

如果你正常打电话

function foo() { console.log(this); }

function foo() { console.log(this); } foo(); 将成为全球对象。

如果你处于严格模式

this

这将是`use strict`; function foo() { console.log(this); } foo(); // or function foo() { `use strict`; console.log(this); } foo();

你可以使用undefinedthis直接设置call

apply

您还可以使用点运算符function foo(msg) { console.log(msg, this); } const obj1 = {abc: 123} const obj2 = {def: 456} foo.call(obj1, 'hello'); // prints Hello {abc: 123} foo.apply(obj2, ['hi']); // prints Hi {def: 456} 隐式设置this

.

如果要将函数用作回调或侦听器,则会出现问题。您创建类并希望将函数指定为访问类实例的回调。

function foo(msg) { console.log(msg, this); }
const obj = {
   abc: 123,
   bar: foo,
}
obj.bar('Hola');  // prints Hola {abc:123, bar: f}

上面的代码不起作用,因为当元素触发事件并调用函数时,class ShowName { constructor(name, elem) { this.name = name; elem.addEventListener('click', function() { console.log(this.name); // won't work }); } } 值将不是类的实例。

解决该问题的一种常见方法是使用this

.bind

因为箭头语法做了我们可以编写的相同的事情

class ShowName {
  constructor(name, elem) {
    this.name = name;
    elem.addEventListener('click', function() {
       console.log(this.name); 
    }.bind(this); // <=========== ADDED! ===========
  }
}

class ShowName { constructor(name, elem) { this.name = name; elem.addEventListener('click',() => { console.log(this.name); }); } } 有效地发挥了新功能。如果bind不存在你基本上可以这样做自己

bind

在没有传播运算符的旧JavaScript中,它将是

function bind(funcitonToBind, valueToUseForThis) {
  return function(...args) {
    functionToBind.call(valueToUseForThis, ...args);
  };
}

理解该代码需要function bind(funcitonToBind, valueToUseForThis) { return function() { functionToBind.apply(valueToUseForThis, arguments); }; } ,但短版本是an understanding of closures创建一个新函数,始终使用绑定到它的bind值调用原始函数。箭头函数做同样的事情,因为它们是this的捷径

© www.soinside.com 2019 - 2024. All rights reserved.