Extend can add properties to an existing object or copy the properties from other objects into an existing object.
Extend is called like this: _.extend(obj);
Yep, that's it. You feed it the object that you want added to , and then you either fill in a bunch of these : {example : example} or names of other objects.
Inside the extend function the arguments array will be accessed. If you don't know what the arguments object is, I would go ahead an google it. You'll need to learn about it at some point.
So, extend is rewritten like this:
_.extend = function(obj) {
_.each(arguments, function(item){
_.each(item, function(value, prop){
obj[prop] = value
})
})
return obj;
}
Pretty simple. It's a function that takes an object as an argument, and like any function, can take any number of arguments.
It calls each and feed it the its own argumentsobject, which is accessed with the keyword arguments.
The arguments object is similar to an array, but the only array property is has is .length.
The first each accesses each item in the arguments object, the second each iterates through each item, grabbing the key and the value in each obj, and then assigns the new key and value to the existing obj.
Finally, the object is returned.
If this confuses you, I would suggest making an array of objects and playing around with it.
No comments:
Post a Comment