0

Using just JavaScript and not a library such as jQuery, is there a more elegant way (such as jquery.extend()) to modify an object before passing it to a function?

var o={
    a:1,
    b:2,
    c:3,
    d:function(){alert('f');}
};
o.e='abc';
o.f='cba';
o.g=function(){alert ('f1');};
foo(o);
o.e='xyz';
o.f='zyx';
o.g=function(){alert ('f2');};
foo(o);

1 Answer 1

1

Modern browsers other than any version of Internet Explorer (according to MDN anyway) support Object.assign(), which is more or less the same as jQuery.extend() other than its one-argument semantics.

foo(Object.assign(o, { e: "abc", f: "cba" }));

Should be available in Node too (again, ES2015 versions).

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks Pointy. That was exactly what I was looking and hoping for, however, not being supported by any version of IE poses some problems.
There's what appears to be a decent polyfill on the MDN page.
Works on IE Edge. jsfiddle.net/813f1j24. Interestingly, console.log in Firebug shows the same values. Actually, Firefox works, but firebug displays the wrong values. jsfiddle.net/813f1j24/1
@torazaburo if you call jQuery.extend({foo: "hi"}) you're extending the jQuery prototype. So it's like $.extend($.fn, {foo: "hi"});
at least I think that's true; it might be $ - I'll check. edit grr, jQuery docs are vague, and refer to "the jQuery namespace".
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.