//非构造函数继承
var persion = {
age:24
}
var student = {
identity:'student'
}
//1.object方法
function object(o){
function f(){};
f.prototype = o;
return new f();
}
var student = object(persion);
console.log("identity:"+student.identity+" age:"+student.age);
//这里的identity是undefined 因为student自己的属性被覆盖掉了,需要在继承后才加上自己的属性
student.identity = "student";
console.log("identity:"+student.identity+" age:"+student.age);
//2浅拷贝方法
function extendCopy(parent){
var c = {};
for(var i in parent){
c[i] = parent[i];
}
return c;
}
/*
这种方法如果遇到parent属性也是一个对象或数组的时候,
属性值其实是一个内存地址,这样会出parent改变那个对象属性,继承的子类也会跟着变
这样就不准了
*/
//深拷贝——递归调用浅拷贝就能实现深拷贝
function deepCopy(c,parent){
var c = c||{};
for(var i in parent){
if(typeof c[i] == "ojbect"){
c[i] = (parent[i].constructor === Array)?[]:{};
deepCopy(c[i],parent[i]);
}else{
c[i] = parent[i];
}
}
return c;
}
var a = {
name:"a"
}
var p = {
age:24,
role:{code:404,msg:"msg"}
}
deepCopy(a,p);
a.name = "I am a";
console.log("name:"+ a.name+" code:"+ a.role.code+" msg:"+ a.role.msg+" age"+ a.age);
参考自:阮一峰