我知道 >=
运算符意味着大于或等于,但我在一些源代码中看到过 =>
。该运算符的含义是什么?
代码如下:
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) {...}
之类的表达式。但它们有一些重要的区别。例如,它们不绑定(bind)自己的 this
值(请参阅下面的讨论)。
箭头函数是 ECMAscript 6 规范的一部分。并非所有浏览器都支持它们,但部分或完全支持它们 in Node v. 4.0+以及截至 2018 年使用的大多数现代浏览器中。(我在下面列出了支持浏览器的部分列表)。
You can read more in the Mozilla documentation on arrow functions .
来自 Mozilla 文档:
An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the
this
value (does not bind its ownthis
,arguments
,super
, ornew.target
). Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.
关于 this
在箭头函数中如何工作的注释
箭头函数最方便的功能之一隐藏在上面的文本中:
An arrow function... lexically binds the
this
value (does not bind its ownthis
...)
简单来说,这意味着箭头函数保留其上下文中的 this
值,并且没有自己的 this
。传统函数可能绑定(bind)自己的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(22 版以上)
- Edge(12 版以上)
- 歌剧(32 节以上)
- Android 浏览器(v. 47+)
- Opera Mobile(v. 33+)
- Android 版 Chrome(47 版以上)
- Android 版 Firefox(44 版以上)
- Safari(v. 10+)
- iOS Safari(v. 10.2+)
- 三星互联网(v. 5+)
- 百度浏览器(v. 7.12+)
不支持:
- IE(至第 11 版)
- Opera Mini(至 8.0 版)
- Blackberry 浏览器(至第 10 版)
- IE 移动版(至第 11 版)
- Android 版 UC 浏览器(截至 11.4 版)
- QQ(截至 1.2 版)
您可以在 CanIUse.com 找到更多(以及更多当前)信息。 (无隶属关系)。
关于javascript - JavaScript 中的 "=>"(由等于和大于组成的箭头)是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35220585/