我知道>=
运算符意味着大于或等于,但我在一些源代码中看到过=>
。那个运营商的意义是什么?
这是代码:
promiseTargetFile(fpParams, aSkipPrompt, relatedURI).then(aDialogAccepted => {
if (!aDialogAccepted)
return;
saveAsType = fpParams.saveAsType;
file = fpParams.file;
continueSave();
}).then(null, Components.utils.reportError);
这是一个箭头功能。箭头函数是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
值(不绑定其自己的this
,arguments
,super
或new.target
)。箭头功能始终是匿名的。这些函数表达式最适合非方法函数,不能用作构造函数。
this
如何在箭头函数中起作用的注记箭头函数最方便的功能之一隐藏在上面的文本中:
箭头函数...词法上绑定
this
值(不绑定自己的this
......)
这意味着简单来说,箭头函数保留了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日,当前版本支持:
不支持:
您可以在CanIUse.com(无联盟)找到更多(和更新的)信息。
正如所有其他答案已经说过的那样,它是ES2015箭头函数语法的一部分。更具体地说,它不是一个运算符,它是一个标点符号,用于将参数与正文分开:bind(this)
。例如。 ArrowFunction : ArrowParameters => ConciseBody
。
(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
用符号(=>)表示的箭头函数可以帮助您创建匿名函数和方法。这导致更短的语法。例如,下面是一个简单的“添加”功能,它返回两个数字的相加。
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”调用,我们希望它显示“本地上下文”,但它显示“全局上下文”。
但如果使用箭头功能替换呼叫,它将显示“本地上下文”。
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这个术语。
这被称为箭头功能,是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
另一个很棒的东西是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();
更多信息,here's是何时使用箭头功能的一个很好的答案。
这将是ECMAScript 6中引入的“箭头函数表达式”。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/arrow_functions
出于历史目的(维基页面稍后更改),它是:
与函数表达式相比,箭头函数表达式具有更短的语法,并且词汇绑定此值。箭头功能始终是匿名的。
只是为了添加一个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
也称为Fat Arrow Functions。它们是编写函数表达式的简洁明了的方法,例如qazxsw poi。
箭头函数可以在定义函数时消除function() {}
,function
和return
的需要。它们是单行的,类似于Java或Python中的Lambda表达式。
{}
如果需要在同一个箭头函数中进行多个语句,则需要在curley括号const queue = ['Dave', 'Sarah', 'Sharon'];
const nextCustomer = () => queue[0];
console.log(nextCustomer()); // 'Dave'
中包装queue[0]
。在这种情况下,不能省略return语句。
{}
您可以从上面省略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]
。
可以在浏览器兼容性here上找到其他最新信息
正如其他人所说,这是一种创建函数的新语法。
但是,这种功能与正常功能不同:
this
所解释的那样,
ArrowFunction不为the spec,arguments
,super
或this
定义局部绑定。在ArrowFunction中对new.target
,arguments
,super
或this
的任何引用必须在词汇封闭环境中解析为绑定。通常,这将是直接封闭函数的函数环境。
即使ArrowFunction可能包含对new.target
的引用,步骤4中创建的函数对象也不会通过执行super
而成为方法。引用MakeMethod的ArrowFunction总是包含在非ArrowFunction中,并且可以通过ArrowFunction的函数对象捕获的作用域访问实现super
的必要状态。super
我读过,这是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 );
使用箭头功能添加简单的CRUD示例
MDN Docs
对其他答案不满意。截至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);
,也不需要function
和return
,甚至不需要括号或括号
稍微长一点的箭头函数可能是
.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();
你可以使用undefined
或this
直接设置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
的捷径