/*Prototypal Inheritance*/
function object(o) {
function F() { }
F.prototype = o;
return new F();
}
// object to inherit from
var parent = {
name: "Papa"
};
// the new object
var child = object(parent);
// testing
alert(child.name); // "Papa"
//used in function
function Person() {
// an "own" property
this.name = "Adam";
}
// a property added to the prototype
Person.prototype.getName = function () {
return this.name;
};
// create a new person
var papa = new Person();
// inherit
var kid = object(papa);
// test that both the own property
// and the prototype property were inherited
kid.getName(); // "Adam"
/*shallow copy*/
function extend(parent, child) {
var i;
child = child || {};
for (i in parent) {
if (parent.hasOwnProperty(i)) {
child[i] = parent[i];
}
}
}
/*Deep Copy*/
function extendDeep(parent, child) {
var i,
toStr = Object.prototype.toString,
astr = "[object Array]";
child = child || {};
for (i in parent) {
if (parent.hasOwnProperty(i)) {
if (typeof parent[i] === "object") {
child[i] = (toStr.call(parent[i]) === astr) ? [] : {};
extendDeep(parent[i], child[i]);
} else {
child[i] = parent[i];
}
}
}
return child;
}