拷贝继承顾明思议就是讲需要继承的父类构造函数原型方法通过遍历添加到子类构造函数的原型上,从而使子类构造函数原型或者子类实例具备父类构造函数原型的属性和方法(只能遍历父类构造函数原型可被遍历的属性。因为,可能存在不可被遍历的属性跟方法)
例如:
function Objfather(){
this.type = "人类"
}
Objfather.prototype = {
constructor:Objfather,
test:{
a:"1",
b:"2"
}
example:function(){
console.log("吃饭")
}
}
function Objchidren(name,age){
this.name = name;
this.age = age;
}
拷贝分为深拷贝跟浅拷贝。个人认为,浅拷贝跟深拷贝的区别就是。深拷贝在浅拷贝的基础上做了递归
function protominix(father,chidren) { //浅拷贝
var fatherproto = father.prototype,
chidrenproto = chidren.prototype;
for (i in father.prototype){
chidrenproto[i] = fatherproto[i]
}
return chidren
}
for (i in father.prototype){ //深拷贝的话替换for in循环(只是加了判断做递归) if(typeof father.prototype[i] == Object){ protominix(father.prototype[i],chidrenproto[i]) }else{ chidrenproto[i] = fatherproto[i] } } 跟上一篇分享文章一样,如果改变了constructor属性的指向就执行 Objchidren.prototype.constructor = Objchidren; protominix(Objfather,Objchidren); var chidren1 = new Objchidren("小明",12); console.log(chidren1.__proto__); 跟之前分享的直接继承父构造函数的prototype不同之处在于 直接继承父构造函数的prototype,这时改变子构造函数的prototype会引发父构造函数原型的改动。因为对象属于复杂数据类型。而复杂数据类型的赋值是引用的赋值,跟简单数据类型的赋值是不一样的(详见犀牛书有详细的说明) 而拷贝之后修改子构造函数原型不会引发父构造函数原型的变化。 例如: 在var chidren1 = new Objchidren("小明",12);之前修改原型 Objchidren.prototype.example = function(){ console.log("食物搭配要合理") } console.log(Objfather.prototype.example) //这里依然是父构造函数的原型