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

代码如下:

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

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

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

当前回答

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

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

通过使用如下所示的“箭头”语法,上面的函数变得更短。

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

输入:—指定匿名函数的输入参数。

逻辑:-这部分出现在符号“=>”之后。本节符合实际函数的逻辑。

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

如果你相信上面这句话,那么让我向你保证这是一个神话。如果你想一下,一个正确编写的带有名称的函数比在一行中使用箭头符号创建的神秘函数更具可读性。

箭头函数的主要用途是确保代码运行在 呼叫者上下文。

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

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

var context = “global context”;

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

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

var instance = new SomeMethod();

但是如果使用Arrow函数替换调用,它将显示“本地上下文”。

var context = "global context";
   
    function SomeMethod(){
        this.context = "local context";
        SomeOtherMethod = () => {
            alert(this.context);
        }
        SomeOtherMethod();
    }
    var instance = new SomeMethod();

我鼓励你阅读这个链接(JavaScript中的箭头函数),它解释了JavaScript上下文的所有场景,以及在哪些场景中调用者上下文不受尊重。

你也可以在我制作的youtube视频中看到用javascript演示的箭头函数,它实际上演示了上下文这个术语。

其他回答

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

但这类函数与普通函数不同:

They bind the this value. As explained by the spec, An ArrowFunction does not define local bindings for arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically this will be the Function Environment of an immediately enclosing function. Even though an ArrowFunction may contain references to super, the function object created in step 4 is not made into a method by performing MakeMethod. An ArrowFunction that references super is always contained within a non-ArrowFunction and the necessary state to implement super is accessible via the scope that is captured by the function object of the ArrowFunction. They are non-constructors. That means they have no [[Construct]] internal method, and thus can't be instantiated, e.g. var f = a => a; f(123); // 123 new f(); // TypeError: f is not a constructor

这被称为箭头函数,是ECMAScript 2015规范的一部分…

Var foo = ['a', 'ab', 'abc']; Var bar = foo。Map (f => f.length); console.log(栏);/ / 1、2、3

比前面的语法更短:

// < es6: Var foo = ['a', 'ab', 'abc']; Var bar = foo.map(函数(f) { 返回f.length; }); console.log(栏);/ / 1、2、3

DEMO

另一件很棒的事情是词汇上的。通常,你会这样做:

函数Foo() { This.name = name; 这一点。计数= 0; this.startCounting (); } Foo.prototype.startCounting = function() { Var self = this; setInterval(函数(){ //这是窗口,而不是Foo{},因为你可能期望 console.log(这个);//[对象窗口] //这就是为什么我们在setInterval()之前重新分配给self console.log (self.count); self.count + +; }, 1000) } 新Foo ();

但可以用箭头这样重写:

函数Foo() { This.name = name; 这一点。计数= 0; this.startCounting (); } Foo.prototype.startCounting = function() { setInterval(() => { console.log(这个);// [object对象] console.log (this.count);// 1, 2, 3 this.count + +; }, 1000) } 新Foo ();

DEMO

中数 更多关于语法

这里有一个关于何时使用箭头函数的很好的答案。

对其他答案不满意。截至2019/3/13投票最多的答案实际上是错误的。

简单来说,=>的意思是,它是一个编写函数AND的快捷方式,用于将它绑定到当前的this

const foo = a => a * 2;

是有效的捷径吗

const foo = function(a) { return a * 2; }.bind(this);

你可以看到所有被缩短的地方。我们不需要function、return、.bind(this),甚至不需要大括号或圆括号

箭头函数的一个稍微长一点的例子是

const foo = (width, height) => {
  const area = width * height;
  return area;
};

如果我们想要函数的多个参数,我们需要圆括号,如果我们想要写多个表达式,我们需要大括号和显式返回。

理解.bind部分很重要,这是一个很大的主题。这与JavaScript中的含义有关。

所有函数都有一个隐式形参this。在调用函数时如何设置此值取决于该函数的调用方式。

Take

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

如果正常的话

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

这将是全局对象。

如果你处于严格模式

`use strict`;
function foo() { console.log(this); }
foo();

// or

function foo() {
   `use strict`;
   console.log(this);
 }
foo();

它是没有定义的

你可以直接使用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}

您还可以使用点操作符隐式地设置此值。

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不存在,你基本上可以像这样创建自己的

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

在没有展开运算符的旧JavaScript中,它是

function bind(functionToBind, valueToUseForThis) {
  return function() {
    functionToBind.apply(valueToUseForThis, arguments);
  };
}

理解这些代码需要理解闭包,但简单来说,bind创建了一个新函数,它总是调用带有绑定到它的this值的原始函数。箭头函数做同样的事情,因为它们是bind(this)的快捷方式

再举一个例子,说明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

JavaScript箭头函数大致相当于python中的lambda函数或Ruby中的块。这些是具有自己特殊语法的匿名函数,并在其封闭作用域的上下文中操作。这意味着它们没有自己的“This”,而是从直接的封闭函数中访问one。

来自ECMA标准:

ArrowFunction不为参数定义本地绑定, 超级,这个,或者新的目标。任何对参数、super、this或new的引用。ArrowFunction中的target必须解析为 在词汇封闭的环境中绑定。通常这将是 直接封闭函数的函数环境。

通常你会读成“箭头函数表达式是传统函数表达式的紧凑替代”,这是不正确的。箭头函数不是传统函数的简写,它们的行为与传统函数不同。

语法

// Traditional Function
// Create their own scope inside the function
function (a){
  return a + 100;
}

// Arrow Function 
// Do NOT create their own scope
// (Each step along the way is a valid "arrow function")

// 1. Remove the word "function" and place arrow between the argument and opening body bracket
(a) => {
  return a + 100;
}

// 2. Remove the body braces and word "return" -- the return is implied.
(a) => a + 100;

// 3. Remove the argument parentheses (only valid with exactly one argument)
a => a + 100;