博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

js reuse code object copy

Posted on 2011-12-17 21:07  ritazhou  阅读(331)  评论(0编辑  收藏  举报
/*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;
}