前言:我们在网上可以看到继承的方法有很多种,其实本质上就只有三种。就是一下三种。
一、构造函数继承
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name);
};
Person.prototype.sayAge = function(){
console.log(this.age);
};
function Child(name,age){
Person.call(this,name,age);
}
Child.prototype = new Person;
// 构造函数的原型是一个对象,这是我们把 Person 实例放在这里,
通过 Person 的实例对象就可以拿到Person 的prototype的所有方法
var child = new Child("kkb",8);
console.log(child);
二、原型继承
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name);
};
Person.prototype.sayAge = function(){
console.log(this.age);
};
function Child(name,age){
Person.call(this,name,age);
}
function extend(Parent){
function F(){}//F是个空函数
F.prototype = Parent.prototype; // 让 F 的原型等于 父类的原型就拿到父类的原型,
这样的话,实例化对戏时,就只有 原型中的内容,没有实例中的内容
return new F;
}
Child.prototype = extend(Person);
Child.prototype.constructor = Child;
Child.prototype.sayAge = function(){
console.log("就不告诉你年龄");
}
// 构造函数的原型是一个对象,这是我们把 Person 实例放在这里,通过 Person 的实例对象就可以拿到Person 的prototype的所有方法
var miaov = new Person("miaov",9)
var kkb = new Child("kkb",8);
miaov.sayAge();
kkb.sayAge();
三、拷贝继承
浅拷贝继承
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name);
};
Person.prototype.sayAge = function(){
console.log(this.age);
};
function Child(name,age){
Person.call(this,name,age);
}
//Child.prototype = Person.prototype;
// 注意 prototype 本身是一个对象,对象是传址的,如果把父类的 Person.prototype 直接赋值给 Child,
我们修改了 Child.prototype 之后, Person.prototype 也有改变
// 浅拷贝
// for(var s in Person.prototype){
// Child.prototype[s] = Person.prototype[s];
// }
// 浅拷贝只考虑第一层的引用问题
// 深拷贝考虑每一层的引用问题
Child.prototype = {...Person.prototype};
Child.prototype.sayAge = function(){
console.log("就不告诉你年龄");
}
var miaov = new Person("miaov",9)
var kkb = new Child("kkb",8);
miaov.sayAge();
kkb.sayAge();
深拷贝继承
function copy(data){
if(typeof data === "object"){ // 对象类型 要进行拷贝
if(Array.isArray(data)){
var arr = []; // 数组复制数组的每一项
for(var i = 0; i < data.length; i++){
arr[i] = copy(data[i]);
}
return arr;
} else {
var obj = {}; //对象类型复制对象的每一项
for (var s in data) {
obj[s] = copy(data[s]);
}
return obj;
}
}
return data;
}
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name);
};
Person.prototype.sayAge = function(){
console.log(this.age);
};
function Child(name,age){
Person.call(this,name,age);
}
//Child.prototype = Person.prototype;
// 注意 prototype 本身是一个对象,对象是传址的,如果把父类的 Person.prototype 直接赋值给 Child,我们修改了 Child.prototype 之后, Person.prototype 也有改变
// 浅拷贝
// for(var s in Person.prototype){
// Child.prototype[s] = Person.prototype[s];
// }
// 浅拷贝只考虑第一层的引用问题
// 深拷贝考虑每一层的引用问题
Child.prototype = copy(Person.prototype);
Child.prototype.sayAge = function(){
console.log("就不告诉你年龄");
}
var miaov = new Person("miaov",9)
var kkb = new Child("kkb",8);
miaov.sayAge();
kkb.sayAge();