In the Lodash library, what is the value of using _.create()
to handle classes and instances vs other more traditional methods?
Asked
Active
Viewed 1,880 times
2

JDillon522
- 19,046
- 15
- 47
- 81
-
2looks like a shim for `Object.create`. – Daniel A. White Mar 10 '15 at 16:10
-
@DanielA.White: but not exactly, as the second argument doesn't consist of property descriptors. – Bergi Mar 10 '15 at 16:14
-
possible duplicate of [Using “Object.create” instead of “new”](http://stackoverflow.com/q/2709612/1048572) (and similar questions). Please [edit] your question to elaborate on what you mean by "more traditional methods", or we'll need to close it. – Bergi Mar 10 '15 at 16:15
-
When you say "what is the value of using _.create()" do you mean as apposed to not using low dash at all and creating objects differently, or do you mean as opposed to still using lowdash but creating objects without _.create? – atmd Mar 10 '15 at 16:27
-
I mean what is the value of using `_.create()` to handle inheritance vs any other way of handling inheritance (like the standard `Class.prototype.method_name = function()...` – JDillon522 Mar 10 '15 at 16:35
-
@JDillon522: That does different things. Depends on what you need. – Bergi Mar 10 '15 at 20:19
-
yeah i figured. I'd like to know what the differences are so I know when to use what. – JDillon522 Mar 10 '15 at 20:20
3 Answers
2
I don't think create() is meant to replace the existing JavaScript inheritance/prototype mechanisms. In my experience, it's been convenient when mapping collections of one type to another:
function Circle(x, y) {
this.x = x;
this.y = y;
}
function Square(x, y) {
this.x = x;
this.y = y;
}
Square.prototype.coords = function() {
return [ this.x, this.y ];
}
var collection = [
new Circle(1, 1),
new Circle(2, 2),
new Circle(3, 3),
new Circle(4, 4)
];
_(collection)
.map(_.ary(_.partial(_.create, Square.prototype), 1))
.invoke('coords')
.value();
// →
// [
// [ 1, 1 ],
// [ 2, 2 ],
// [ 3, 3 ],
// [ 4, 4 ]
// ]

Adam Boduch
- 11,023
- 3
- 30
- 38
1
I think of it as a convenience. It's a little more succinct when doing the common task of implementing a classical inheritance model in JS.
Natively:
var User = function() {};
User.prototype = Object.create(Person.prototype);
Object.assign(User.prototype, {
constructor: User,
...other stuff
});
versus _.create
:
var User = function() {};
User.prototype = _.create(Person.prototype, {
constructor: User,
...other stuff
});
It's just a little less to write.

jamesplease
- 12,547
- 6
- 47
- 73
0
The biggest difference i see after reading some of the lodash code is that Object.create second argument, takes the format of the object.defineProperty arg, that being a property descriptor, while _.create just copies all the own or inherited enumerable properties (relies on nativeKeysIn) from the object.
It mainly eases classical object definition.

Nicolas NZ
- 368
- 3
- 5