Skip to content

Commit 9145932

Browse files
committed
Merge pull request #2074 from jridgewell/create
Add _.create method
2 parents 9ac45c6 + b407498 commit 9145932

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

test/objects.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,32 @@
282282
equal(_.clone(null), null, 'non objects should not be changed by clone');
283283
});
284284

285+
test('create', function() {
286+
var Parent = function() {};
287+
Parent.prototype = {foo: function() {}, bar: 2};
288+
289+
_.each(['foo', null, undefined, 1], function(val) {
290+
deepEqual(_.create(val), {}, 'should return empty object when a non-object is provided');
291+
});
292+
293+
ok(_.create([]) instanceof Array, 'should return new instance of array when array is provided');
294+
295+
var Child = function() {};
296+
Child.prototype = _.create(Parent.prototype);
297+
ok(new Child instanceof Parent, 'object should inherit prototype');
298+
299+
var func = function() {};
300+
Child.prototype = _.create(Parent.prototype, {func: func});
301+
strictEqual(Child.prototype.func, func, 'properties should be added to object');
302+
303+
Child.prototype = _.create(Parent.prototype, {constructor: Child});
304+
strictEqual(Child.prototype.constructor, Child);
305+
306+
Child.prototype.foo = 'foo';
307+
var created = _.create(Child.prototype, new Child);
308+
ok(!created.hasOwnProperty('foo'), 'should only add own properties');
309+
});
310+
285311
test('isEqual', function() {
286312
function First() {
287313
this.value = 1;

underscore.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1048,6 +1048,15 @@
10481048
// Fill in a given object with default properties.
10491049
_.defaults = createAssigner(_.allKeys, true);
10501050

1051+
// Creates an object that inherits from the given prototype object.
1052+
// If additional properties are provided then they will be added to the
1053+
// created object.
1054+
_.create = function(prototype, props) {
1055+
var result = baseCreate(prototype);
1056+
if (props) _.assign(result, props);
1057+
return result;
1058+
};
1059+
10511060
// Create a (shallow-cloned) duplicate of an object.
10521061
_.clone = function(obj) {
10531062
if (!_.isObject(obj)) return obj;

0 commit comments

Comments
 (0)