繁体   English   中英

使函数参数强制的最佳方法是什么?

[英]What's the best way to make a parameter of a function mandatory?

在Coffeescript中,用必需参数创建函数的最佳方法是什么? 目前,我正在这样做:

myFunction: (requiredParam, optionalParam) ->
    unless requiredParam? then throw new Error ...
    ...

如果我有5个甚至更多的参数,则花费大量时间和空间为每个参数抛出错误。

有没有更简单/更简洁的方法?

您可以在任何函数内使用arguments变量,以确保实际参数的数量不少于所需参数的数量。

myFunction: (required1, required2, required3, optional1, optional2) ->
  throw new Error("Given #{arguments.length} out of 3 required.") if arguments.length < 3
  # ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM