In Lodash, both
_.assignIn are ways to copy source objects’ properties into target object. According the documentation,
_.assign processes own enumerable string keyed properties, while
_.assignIn processes both own and inherited source properties. There’re also other companion functions like
_.hasIn. So what’s the difference between them?
In brief, the
In in latter methods implies the way
_.forIn, all properties appeared in the object and its prototype are processed, until the prototype resolves to
null. Here’s the example code taken from Lodash’s doc:
Let’s dissect the phrase “own enumerable string-keys properties” into three parts.
Object.create, and the newly added
class keyword. In either case, we can use
Object.prototype.hasOwnProperty() to determine if the property is inherited or not.
Object.keys() can retrieve all properties defined directly in the object, except that
Object.keys() only returns enumerable keys (see next section).
Object property can be defined with either data descriptor or accessor descriptor. Among data descriptor options, the
enumerable boolean indicates whether this property shows in
You can refer to Object.defineProperty() for more information.
Before ES6, object’s keys are always String. ES6 introduces a new primitive type Symbol, which can be used as a key for private property. Symbol property is non-enumerable.
There’s a nice Detection Table to help you figure out which built-in methods process enumerable or inherited properties.
Both methods calls
for...in loop. Actually
Object.keys() is not difficult to implement. As mentioned above,
for...in can be used to retrieve both own and inherited properties, while
hasOwnProperty determines whether this property is defined in the object itself.
Object.assign() does the same thing as
_.assign(). Use Lodash if you need to run your code on older browsers.