JS:有一个新的运算符"=>&”;

JS: there is a new operator "=>"

本文关键字:quot gt 运算符 有一个 JS      更新时间:2023-09-26

我正在尝试构建黄油(https://github.com/butterproject/butter-desktop)但它没有编译,因为hoek库中的一个代码:

/src/butter-desktop/node_modules/hawk/node_modules/hoek/lib/index.js:483
compare = (a, b) => a === b;
                  ^
...
>> Unexpected token >

还有其他行使用了这个"运算符"=>,比如:

    const leftovers = ref.replace(regex, ($0, $1) => {
        const index = values.indexOf($1);
        ++matches[index];
        return '';          // Remove from string
    });

我试图理解,我想这就像一个"函数"运算符。。。

如果我得到了正确的东西类似于:

第一个代码:

compare = (function(a, b) { return a === b; })(a,b);

在这种情况下与相同

compare = a === b;

和第二个代码:

const leftovers = ref.replace(regex, (function($0, $1) {
        const index = values.indexOf($1);
        ++matches[index];
        return '';          // Remove from string
    })($0, $1));

有人可以确认并给我一个官方参考吗?

在线代码为:https://github.com/hapijs/hoek/blob/master/lib/index.js#L483

这是一个箭头函数。升级到Node.js4.x,这样您就可以使用类似这样的ES6功能。

它是定义箭头函数的运算符,基本上是定义一个不创建新子作用域的函数的新方法。。。

没有什么新鲜事,因为您可以实现将声明的函数与其父作用域绑定的相同行为。。。

以下两个示例:

// ECMASCRIPT 6 ARROW FUNCTION
var fn = () => {
  
  console.log('this is', this);
  
  return true;
}

// ECMASCRIPT 5 ARROW FUNCTION BEHAVIOUR
var fn = function() { 
  console.log('this is', this);
  
  return true;
}.bind(this);