【发布时间】:2018-07-22 06:52:08
【问题描述】:
我在 freecodecamp.org 上做一些 ES6 语法练习,理解上下文有些困难。我知道这在 JS 中称为IIFE,
(function () {
statements
})();
所以,这没关系,但为什么我不能在 first sum 中获得 ..args 而不是仅在内部 sum 中获得?
const sum = (function(...args) {
console.log(...args); //this shows nothing
return function sum(...args) {
console.log(...args); // this shows 1,2,3
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3)); // 6
如果我用这个修改上面的 sn-p 怎么办,他们在做同样的事情吗?引擎盖下是否存在任何逻辑差异?
function sum(...args) {
console.log(args);
return args.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6
主要问题是为什么一个函数
sum返回另一个函数sum在里面。
【问题讨论】:
-
Uncaught SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list -
@CertainPerformance 已编辑,只是复制粘贴 :)
标签: javascript function ecmascript-6