在Object的原型链上添加方法。
Object.prototype.deepCopy = function() {
// var obj = Object.create(this.__proto__);
var obj = {};
if (this.__proto__ && this.__proto__.deepCopy)
{
obj.__proto__ = this.__proto__.deepCopy();
}else
{
return ;
}
var keys = Object.keys(this); //也可用hasOwnProperty的方法获取非原型链上的方法。
var self = this;
keys.forEach(function(val, index) {
obj[val] = typeof self[val] === 'object' ? self[val].deepCopy() : self[val];
});
return obj;
}
测试下
function Person() {
this.livePlace = 'china';
}
function Man() {
this.sex = 'male';
}
function Baby(name) {
this.age = 5;
this.name = name || 'larry';
}
Man.prototype = new Person();
Baby.prototype = new Man();
var b1 = new Baby();
console.log(b1);
console.log(b1.deepCopy());