/*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;
}

相关文章:

  • 2021-04-21
  • 2021-12-11
  • 2021-07-08
  • 2021-05-31
  • 2022-12-23
  • 2021-07-15
  • 2022-12-23
  • 2021-10-19
猜你喜欢
  • 2021-09-16
  • 2021-08-17
  • 2022-12-23
  • 2022-12-23
  • 2022-01-25
  • 2021-05-29
  • 2022-12-23
相关资源
相似解决方案