我知道>=运算符意味着大于或等于,但我在一些源代码中看到过=>。这个运算符是什么意思?
代码如下:
promiseTargetFile(fpParams, aSkipPrompt, relatedURI).then(aDialogAccepted => {
if (!aDialogAccepted)
return;
saveAsType = fpParams.saveAsType;
file = fpParams.file;
continueSave();
}).then(null, Components.utils.reportError);
这被称为箭头函数,是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
中数
更多关于语法
这里有一个关于何时使用箭头函数的很好的答案。
正如其他人所述,常规(传统)函数使用调用该函数的对象的this(例如,被单击的按钮)。相反,箭头函数使用定义该函数的对象中的this。
考虑两个几乎相同的函数:
regular = function() {
' Identical Part Here;
}
arrow = () => {
' Identical Part Here;
}
下面的代码段演示了这对于每个函数所代表的内容之间的基本区别。常规函数输出[object HTMLButtonElement],而箭头函数输出[object Window]。
<html>
<button id="btn1">Regular: `this` comes from "this button"</button>
<br><br>
<button id="btn2">Arrow: `this` comes from object that defines the function</button>
<p id="res"/>
<script>
regular = function() {
document.getElementById("res").innerHTML = this;
}
arrow = () => {
document.getElementById("res").innerHTML = this;
}
document.getElementById("btn1").addEventListener("click", regular);
document.getElementById("btn2").addEventListener("click", arrow);
</script>
</html>
ES6 Arrow功能:
在javascript中=>是箭头函数表达式的符号。箭头函数表达式没有自己的this绑定,因此不能用作构造函数。例如:
Var单词= 'hi从外部对象';
让obj = {
Words: 'hi from inside object',
Talk1:() => {console.log(this.words)},
Talk2: function () {console.log(this.words)}
}
obj.talk1 ();//没有它自己的this绑定,this ===窗口
obj.talk2 ();//有它自己的this绑定,这是obj
箭头函数的使用规则:
如果只有一个参数,可以省略参数的括号。
如果你在同一行返回一个表达式,你可以省略{}和return语句
例如:
val * 2;
//它在同一行,返回一个表达式,因此省略{},表达式隐式返回
//也只有一个参数,因此参数周围的括号被省略
console.log (times2 (3));