Passing named arguments to a Javascript function [duplicate]

丶灬走出姿态 提交于 2019-12-12 15:15:24

问题


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');

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});

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.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/17590410/passing-named-arguments-to-a-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!