显然 arguments.length 不起作用。
我可以将签名更改为 f: (...args) => { if (args.length>0) { ..}; };
但这会从函数声明中删除参数信息。
有什么更好的方法吗?
最佳答案
简短的回答是:“否”或“也许”。
较长的答案是:来自 MDN :
An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own
this
,arguments
,super
, ornew.target
). Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.
箭头函数的主要用途是回调,执行代码就像在其父上下文中执行的一样。从而避免烦人且丑陋的 const that = this;
要求并隐式执行。
由于这个原因,并且由于它是匿名执行的,因此在父级的上下文中,没有参数
,或者更确切地说,值是父级的上下文。箭头函数只能解决一般用例,而不是所有用例。
解决方案 1:遗留或“简单”实现
// const that = this;
var that = this;
...
f: function (a, b, c) {
...
}
...
- 优点
- (目前)比箭头函数稍快
- 拥有自己的上下文(即
参数
等) - 可以在所有浏览器和环境中安全地实现
- 缺点
- 烦人的
that
(或其他一些 var 名称)而不是this
。 - 函数不能是外部的,否则会丢失
那个
引用
方案二:函数绑定(bind)(ES5)
...
f: (function (a, b, c) {
...
}).bind(this)
...
- 优点
- “正确”
这个
可用 - 可以传递任何外部函数引用(即重用代码)
- 拥有自己的上下文(即
参数
等) - 缺点
- (目前)比箭头函数稍慢
- 如果之前绑定(bind)了函数引用,则会出现意外结果
- 不支持 IE8 和其他浏览器(我不得不提到这一点,即使我不太关心 IE8)
方案三:解构赋值(ES6)
...
f: (...args) => {
const [a, b, c] = args;
...
}
g: (a, b, c, ...others) => {
...
}
...
- 优点
- 匿名函数
- 无缝访问父上下文
- 表现出相似的行为
- 缺点
- 可能需要解构
- (目前)比标准函数稍慢
- 不是真正的
参数
实例 - 需要一个转译器(例如:Babel)才能在浏览器中运行,这可能会转译为“遗留”实现
关于javascript - 验证箭头函数参数数量的好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39431937/