Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

underscorejs - what is the difference between extendOwn vs extend?

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!

like image 291
Jonathon Hibbard Avatar asked Mar 12 '15 18:03

Jonathon Hibbard


People also ask

What does _ Extend () do?

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.

Why is JavaScript underscore better?

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.

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

What is underscore min js?

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.


1 Answers

"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
like image 77
johncip Avatar answered Jun 17 '23 00:06

johncip