//非構(gòu)造函數(shù)繼承
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 因?yàn)閟tudent自己的屬性被覆蓋掉了述雾,需要在繼承后才加上自己的屬性
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屬性也是一個(gè)對(duì)象或數(shù)組的時(shí)候兼丰,
屬性值其實(shí)是一個(gè)內(nèi)存地址,這樣會(huì)出parent改變那個(gè)對(duì)象屬性地粪,繼承的子類也會(huì)跟著變
這樣就不準(zhǔn)了
*/
//深拷貝——遞歸調(diào)用淺拷貝就能實(shí)現(xiàn)深拷貝
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);
參考自:阮一峰