gpt4 book ai didi

javascript - ES6 语法的未知含义

转载 作者:行者123 更新时间:2023-11-29 16:07:00 24 4
gpt4 key购买 nike

目前我正在学习 React 和 Redux。我找到了一个样板文件,我正在努力查看所有示例代码。我的问题是我不完全理解很多 ES6 语法的含义。

到目前为止我学到的是 hello = () => "Hello"; 相当于:

hello = function hello() {
return "Hello";
};

然后将上面的内容更改为 hello = name => "Hello "+ name; 会将其转换为:

hello = function hello(name) {
return "Hello " + name;
};

这一切都非常有道理,基本上它只是缩短了它,所以您不必编写函数及其返回语句。然而,我遇到了一些我无法理解的语法。具体如下:

const mapActionCreators = {
increment: () => increment(1),
doubleAsync
}

以上代码转换为:

var mapActionCreators = {
increment: function (_increment) {
function increment() {
return _increment.apply(this, arguments);
}

increment.toString = function () {
return _increment.toString();
};

return increment;
}(function () {
return increment(1);
}),
doubleAsync: doubleAsync
};

我知道 () => increment(1) 在这种情况下被转为:

(function () {
return increment(1);
}),

总的来说,我想我的问题是,increment: 如何转换为:

 increment: function (_increment) {
function increment() {
return _increment.apply(this, arguments);
}

increment.toString = function () {
return _increment.toString();
};

return increment;
}

代码是什么意思?

最佳答案

箭头函数从创建它们的范围中捕获 this 的值。

apply 允许您调用一个函数并在其中显式地调用 this 的值。

其余代码只是将正确的 this 提供给函数。

(如果您尝试将生成的函数字符串化,toString 会确保正确的函数被字符串化)。

关于javascript - ES6 语法的未知含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38882299/

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