javascript - Pass a value to a specific parameter without caring about the position of the parameter -
this question has answer here:
- named parameters in javascript 8 answers
i wondering if possible pass value specific parameter example specifying name, not taking account if parameter first, second or 100th one.
for example, in python can like:
def myfunction(x, y): pass myfunction(y=3);
i need pass value specific parameter of don't know position in parameters enumeration. have searched around while, nothing seems work.
no, named parameters not exist in javascript.
there (sort of) workaround, complex method may take object in place of individual parameters
function dosomething(obj){ console.log(obj.x); console.log(obj.y); }
could called with
dosomething({y:123})
which log undefined
first (the x
) followed 123
(the y
).
you allow parameters optional too, , provide defaults if not supplied:
function dosomething(obj){ var localx = obj.x || "hello world"; var localy = obj.y || 999; console.log(localx); console.log(localy); }
Comments
Post a Comment