Extending an object in js
by JThomas
HTML
<h2>Check the console for the output</h2>
<h4>I recommend Chrome since the debugging tools are better</h4>
CSS
body {
text-align: center;
}
JavaScript
/*
* Reminder: Extending is copying properties from on object to another
* while prototype affects all objects of the specific type
*/
var extender = function (obj) {
var arg = arguments[1];
//Only look at the 2nd argument as it should be an object with properties to add
for (var property in arg) {
//Add the properties from the argument object to the target object
obj[property] = arg[property];
}
return obj;
};
//My new object with an inital property
var baseObject = {
name: "Anonymous Hands"
};
console.log("Before extending:");
console.log(baseObject);
//Let's extend the "myObject" object by adding all the properties from the argument into it
extender(baseObject, {
age: 3,
height: "5'11",
writeMyInfoToConsole: function () {
console.log(this.name + " is " + this.age + " years old.");
}
});
console.log("After extending:");
console.log(baseObject)
baseObject.writeMyInfoToConsole();