Testing Default Objects for Object Instantiation
by Cwalkdawg
JavaScript
var BaseObject = function (initObj) {
this.initObj = initObj;
//Set the properties of the initObj
//as properties of 'this'
this.init = function (objList) {
for (var item in objList) {
if (objList.hasOwnProperty(item)) {
this[item] = objList[item];
}
}
};
//Use this given defaults object to set everything else
this.setDefaults = function (defaults) {
this.defaults = defaults;
this.prototype.init.call(this, this.prototype.initObj);
for (var item in defaults) {
if (defaults.hasOwnProperty(item) && !this.hasOwnProperty(item)) {
this[item] = defaults[item]
}
}
};
};
var Person = function (initObj) {
// Set the prototype to our BaseObject
this.prototype = new BaseObject(initObj);
// Set the defaults in an object
var defaults = {
name: {
first: "John",
middle_initial: null,
last: "Smith"
},
height: 175,
weight: 70
gender: "m"
hair_color: "brown"
ice_cream_favorites: []
};
this.prototype.setDefaults.call(this, defaults);
};
var created = new ConcreteObject({
name: {
first: "Jane",
middle_initial: "P",
last: "Doe"
},
height: 155,
weight: 52,
ice_cream_favorites: ["Strawberry", "Vanilla"]
});
var created2 = new ConcreteObject();
console.log(created);
console.log(created2);