While going through underscorejs's list of methods, I couldn't help but notice a method which I don't remember being there before: extendOwn
The documentation for this method says the following:
extendOwn _.extendOwn(destination, *sources) Alias: assign
Like extend, but only copies own properties over to the destination object.
I understand how .extend() is used and what it does... but for the life of me I cannot understand how it differs from .extendOwn().
I tried using .extend() and then .extendOwn() to extend a few objects just to see if maybe there was something obvious that would happen - but they seem to both produce the same result.
var a = {
foo: false
};
var b = {
bar: true
};
// This will produce { foo: false, bar: true }; ..just like _.extend() would =\
_.extendOwn( a, b );
Any insight into this mystery would be greatly appreciated!
The _. extend() function is used to create a copy of all of the properties of the source objects over the destination object and return the destination object. The nested arrays or objects will be copied by using reference, not duplicated.
It provides utility functions for a variety of use cases in our day-to-day common programming tasks. Underscore. js provides a lot of features that make our task easy to work with objects. It can be used directly inside a browser and also with Node.
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
Underscore. JS is a popular javascript based library which provides 100+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on.
"Own properties" is a technical term in JS. An object's own properties are ones that it didn't inherit.
Here's a short snippet that exposes the different behavior of extend
and extendOwn
:
// lines have length
line = { length: 4 }
// planes have width and inherit length
plane = Object.create(line)
plane.width = 5
plane.length // 4
// making a cube object, using extend
cube = _.extend({ height: 6 }, plane)
cube.length // 4
// making a cube object, using extendOwn
notACube = _.extendOwn({ height: 6 }, plane)
notACube.length // undefined
As you can see, extendOwn
only copied properties that were defined directly on the source, whereas extend
also copied the ones defined along its prototype chain. Also note the symmetry with _.has
:
_.has(plane, 'width') // true
_.has(plane, 'length') // false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With