From 4085b68be458cd401ab82721d409771b9ee4ab5e Mon Sep 17 00:00:00 2001 From: Mike Frawley Date: Sun, 24 Jan 2010 11:53:30 -0600 Subject: [PATCH] enhance #extend to allow taking multiple source objects. This is done in jquery, extjs, and others as well. added tests, no docs --- test/objects.js | 11 ++++++++--- underscore.js | 11 +++++++---- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/test/objects.js b/test/objects.js index b49563f9d..a30b30e94 100644 --- a/test/objects.js +++ b/test/objects.js @@ -25,9 +25,14 @@ $(document).ready(function() { }); test("objects: extend", function() { - var source = {name : 'moe'}, dest = {age : 50}; - _.extend(dest, source); - equals(dest.name, 'moe', 'can extend an object with the attributes of another'); + var result; + equals(_.extend({}, {a:'b'}).a, 'b', 'can extend an object with the attributes of another'); + equals(_.extend({a:'x'}, {a:'b'}).a, 'b', 'properties in source override destination'); + equals(_.extend({x:'x'}, {a:'b'}).x, 'x', 'properties not in source dont get overriden'); + result = _.extend({x:'x'}, {a:'a'}, {b:'b'}); + ok(_.isEqual(result, {x:'x', a:'a', b:'b'}), 'can extend from multiple source objects'); + result = _.extend({x:'x'}, {a:'a', x:2}, {a:'b'}); + ok(_.isEqual(result, {x:2, a:'b'}), 'extending from multiple source objects last property trumps'); }); test("objects: clone", function() { diff --git a/underscore.js b/underscore.js index e57d45bac..0a31cea03 100644 --- a/underscore.js +++ b/underscore.js @@ -432,10 +432,13 @@ return _.filter(_.keys(obj), function(key){ return _.isFunction(obj[key]); }).sort(); }; - // Extend a given object with all of the properties in a source object. - _.extend = function(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; + // Extend a given object with all the properties in given object(s) + _.extend = function(obj) { + var prop; + each(_.rest(arguments), function (source) { + for (prop in source) obj[prop] = source[prop]; + }); + return obj; }; // Create a (shallow-cloned) duplicate of an object.