将命名参数传递给 Javascript 函数 [英] Passing named arguments to a Javascript function

查看:55
本文介绍了将命名参数传递给 Javascript 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用类似的东西调用 Javascript 函数

Calling a Javascript function with something like

someFunction(1, true, 'foo');

不熟悉功能,不是很清楚.

is not very clear without familiarity with the function.

我已经看到并使用了插入注释来命名参数的样式:

I have seen and used the style where comments are inserted to name the arguments:

someFunction(/*itemsToAdd*/1, /*displayLabel*/ true, /*labelText*/ 'foo');

但是当参数超过 3 个或更多时,最好在 JSON 对象中传递参数,这使其与顺序无关,并允许在被调用函数中提供默认值

But when it gets beyond 3 or more parameters, it seems better to pass arguments in a JSON object which makes it order-independent, and allows default values to be provided in the called function

someFunction({'itemsToAdd':1, 'labelText':'foo', 'displayLabel':true});

我的问题是;业内的一般做法是什么,是否有不使用任何这些方法的压倒一切的原因.例如,Lint 不喜欢第二种方法.

My question is; what is the general practice in the industry, and are there overriding reasons for not using any of these methods. Lint for example does not like the second method.

推荐答案

就我个人而言,我只会 grep 函数名称并查看与之相关的注释.维护良好的代码将在函数上方有一个注释,解释参数是什么以及它对它们的作用,如果您需要解释为什么参数是这样的,您可以将其粘贴在函数调用上方.

Personally I'd just grep the function name and take a look at the comment associated with it. Well maintained code will have a comment above the function explaining what the arguments are and what it does with them, and you can just paste that above the function call if you need to explain why your arguments are the way they are.

使用 JSON 传递参数似乎是一种增加不必要的解析开销并可能混淆维护者的方法 - 只需添加更多字段并将 NULL 传递到您想要默认值的字段,您就可以解释为什么在调用注释中传入 NULL,而不是让它们不出现在 JSON 中.

Using a JSON to pass arguments seems like a way to add unnecessary parsing overhead and to possibly confuse the maintainer - just add more fields and pass in NULLs to the fields where you want default values, and you can explain why you're passing in NULLs in the call comment instead of just having them not appear in the JSON.

这篇关于将命名参数传递给 Javascript 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆