javascript - Side-effect free version of Underscore.js default function? -
to initialize object using default values using underscore's default function. according documentation, works this:
var foo = _.defaults(object, *defaults)
it described as:
fill in undefined properties in object values defaults objects, , return object. property filled, further defaults have no effect.
although works fine, there 1 thing stumble upon: side effect of manipulating original object.
if run
var foo = { bar: 'baz' };
and say
var bar = _.defaults(foo, { dummy: 23 });
not only, bar
has property called dummy
, original foo
object has been changed well. current workaround is:
var bar = _.defaults({}, foo, { dummy: 23 });
unfortunately, can forget this. think it's quite strange behavior defaults
function changes input parameter returning result return value. should either or.
how deal situation? there better ways deal this?
the function doing it's documented do. it's not uncommon modify objects passed functions, , it's not uncommon return them. return convenience thing, can write code "workaround."
your "workaround" correct way it.
another option make foo
prototype of new object:
var bar = _.defaults(object.create(foo), { dummy: 23 });
...but know works looking @ annotated source (that link may rot, it'll near there) of underscore, since documentation doesn't specify whether, when copying defaults, looks "own" properties. (it doesn't, uses in
.)
also note object.create
es5 , may require shim on older browsers. use above shimmable (because i'm not using object.create
's second argument).
i re-read title:
side-effect free version of underscore.js default function?
if don't workaround, side-effect-free version easy create:
function mydefaults() { var args = [{}]; args.push.apply(args, arguments); return _.defaults.apply(_, args); }
that creates blank object , puts @ beginning of arguments, chains _.defaults
.
Comments
Post a Comment