gpt4 book ai didi

javascript - 函数与粗箭头

转载 作者:行者123 更新时间:2023-12-01 03:55:34 27 4
gpt4 key购买 nike

所以,如果我们采用这个 function例如:

function executeCallback (callback) {
callback();
}

现在,我是否放置 fat arrow 并不重要。或正常function ,两者都可以工作,如下所示:

executeCallback(function () {
alert('This is a function');
})

executeCallback(() => {
alert('This is a fat arrow function');
})

所以,除了较短的语法。两者之间到底有什么区别?它如何影响面向对象编程?

最佳答案

有关更深入的信息,请参阅 SO 上的此答案。另外,请参阅此here .

一些原因

<小时/>

更直观地处理当前对象上下文。

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; });

关于javascript - 函数与粗箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42721768/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com