Instantly share code, notes, and snippets.

Embed
What would you like to do?
Object.define, Object.assign (or Object.put)

Recently, Allen produced a strawman proposal[0][1] for the "object define properties" operator, which was designed to provide syntax that differentiated semantics of define vs. assign. Towards the end of the thread, IIRC, Brendan suggested some new Object functions: Object.define() and Object.assign().[2]

I spent time over the weekend preparing common use cases for batch assignment based on real world examples from jQuery[3], Dojo[4], Node.js[5] and Lodash (an improved Underscore)[6][7] (With all due respect, Prototype is no longer considered a relevant library for use in modern day web development). Initially, I assumed that the jQuery "deep extend" was the common case and drafted an attempt at handling "nested assignment" or "deep extending". Off-list, Dave Herman reminded me that there is no way to know what the user actually wants with regard to nested object properties:

  1. Target property does not exist: define source value
  2. Target property exists, its value is anything except a nested object: Assign source value

In both cases, "target" refers to an object in the "dictionary of values" or "bag of properties" sense. "source" can be any kind of object that has own properties.

Object.define( target, source ): defineProperties w/ sensible defaults (w, e, c: true), does not copy private names. source is object literal or descriptor map?

Object.put( target, source ): is... "put"! (https://gist.github.com/3350283)

-Rick

[0] https://mail.mozilla.org/pipermail/es-discuss/2012-August/024402.html

[1] http://wiki.ecmascript.org/doku.php?id=strawman:define_properties_operator

[2] https://mail.mozilla.org/pipermail/es-discuss/2012-August/024477.html

[3] https://github.com/jquery/jquery/blob/master/test/unit/core.js#L866-973

[4] http://dojotoolkit.org/reference-guide/1.7/dojo/mixin.html#dojo-mixin

[5] https://github.com/joyent/node/blob/master/test/simple/test-util.js#L73-80 (note: I included this, but primarily, users will require underscore or lodash for such utilities)

[6] https://github.com/bestiejs/lodash/blob/master/test/test.js#L375-399

[7] https://github.com/documentcloud/underscore/blob/master/test/objects.js#L30-41

[8] http://ariya.ofilabs.com/2011/08/hall-of-api-shame-boolean-trap.html

Edit:

YUI APIs:

Y.mix() http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_mix Y.clone() http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_clone Y.merge({}, {}, {})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment