所以,如果我们以function
为例:
function executeCallback (callback) {
callback();
}
现在,如果我放置fat arrow
或正常function
并不重要,两者都会起作用,如下所示:
executeCallback(function () {
alert('This is a function');
})
executeCallback(() => {
alert('This is a fat arrow function');
})
所以,除了更短的语法。两者之间究竟有什么区别?它如何影响面向对象的编程?
答案 0 :(得分:2)
ES6箭头
this.nums.forEach((v) => {
if (v % 5 === 0)
this.fives.push(v) //this actually points to the context of the callback
});
Ecmascript 5
// variant 1
var self = this;
this.nums.forEach(function (v) {
if (v % 5 === 0)
self.fives.push(v);
});
// variant 2
this.nums.forEach(function (v) {
if (v % 5 === 0)
this.fives.push(v);
}, this);
// variant 3 (since ECMAScript 5.1 only)
this.nums.forEach(function (v) {
if (v % 5 === 0)
this.fives.push(v);
}.bind(this));
ES6箭头
odds = evens.map(v => v + 1)
pairs = evens.map(v => ({ even: v, odd: v + 1 }))
nums = evens.map((v, i) => v + i)
Ecmascript 5
odds = evens.map(function (v) { return v + 1; });
pairs = evens.map(function (v) { return { even: v, odd: v + 1 }; });
nums = evens.map(function (v, i) { return v + i; });
答案 1 :(得分:0)
myfunction.bind(this, args)