What is the extend() method in Underscore.js?
Overview
The extend() method in
Syntax
_.extend(obj1, obj2)
Syntax of the extend() method in Underscore.js
Parameters
obj1: This is the object we want to copy the properties of.
obj2: This is the object we want to copy the properties ofobj1into.
Return value
The value returned is an object that contains the properties of both obj1 and obj2.
Example
// require underscoreconst _ = require("underscore")// create some objectslet obj1 = {one: 1, two: 2, three: 3, four: 4}let obj2 = {name: "nodejs", package: "underscore", tag: "_"}let obj3 = {a: "Apple", b: "Banana"}let obj4 = {M: "Monday", T: "Tuesday", W: "Wednesday"}// create other objectslet otherObj1 = {five: 5}let otherObj2 = {method: "extend"}let otherObj3 = {c: "Cherry"}let otherObj4 = {Th: "Thursday"}// get inverted objectsconsole.log(_.extend(obj1, otherObj1));console.log(_.extend(obj2, otherObj2));console.log(_.extend(obj3, otherObj3));console.log(_.extend(obj4, otherObj4));
Explanation
- Line 2: We require the
underscorepackage. - Lines 5–8: We create some objects we want to shallowly copy the properties of.
- Lines 11-–14: We create objects to copy the properties of the other objects we previously created.
- Lines 17–20: With the
extend()method, we shallowly copy the properties of some objects to other ones and print the results to the console.