面试过程中经常会有面试官问 『你知道继承吗』『你说说什么呢是原型链』感觉会,但是不知道怎么说。针对这个,系统的学习了下继承的几种方式,总结出来。
先理解 构造函数、原型、和实例的关系:
每一个构造函数都有一个原型对象,原型对象包含一个指向构造函数的指针,实例包含一个指向原型对象的指针。让原型对象等于另一个类型的实例
此时原型对象将包含指向另一个原型的指针,则构成了原型链
1、原型链继承:
利用原型让一个引用类型继承另一个引用类型的属性和方法
function SuperType() {
this.property = true;
}
SuperType.prototype.getSuperValue = function () {
return this.property;
}
function SubType() {
this.subProperty = false;
}
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.getSubValue = function () {
return this.subProperty;
}
var instance = new SubType();
console.log(instance.constructor);
2、借用构造函数继承
function Father(name, age) {
this.name = name;
this.age = age;
this.sayName = function() {
return this.name;
}
}
function Student() {
Father.call(this, "lisi");
}
var student = new Student();
console.log(student.sayName());
3、组合继承
function Animals(name, age) {
this.name = name;
this.age = age;
this.colors = ["red", "green"];
}
Animals.prototype.sayName = function(){
return this.name;
}
Animals.prototype.sayAge = function(){
return this.age;
}
Animals.prototype.sayColor = function(){
return this.colors;
}
function Sheep() {
Animals.call(this, "yang");
this.age = 13;
}
Sheep.prototype = new Animals();
Sheep.prototype.constructor = Sheep;
var sheep = new Sheep();
sheep.colors.push("white");
console.log(Sheep.prototype.isPrototypeOf(sheep));
var sheep12 = new Sheep();
console.log(Animals.prototype.isPrototypeOf(sheep12));
4、原型式继承
function object(o) {
function f() {}
f.prototype = o;
return new f();
}
var wutong = {
name: "wutong",
friends: ["shangze", "pingan"]
};
var anotherWutong = Object.create(wutong, {name: {
value: "wutong1"
}});
anotherWutong.name = "gren";
anotherWutong.friends.push("feifei");
console.log(anotherWutong);
var anotherWutong1 = Object.create(wutong);
console.log(anotherWutong1.name);
5、寄生式继承
function creatAnother(original) {
var clone = Object.create(original);
clone.sayHi = function() {
console.log(this.name);
}
return clone;
}
var another = {
name: "li9si",
age: 23
}
var anotherPerson = creatAnother(another);
anotherPerson.sayHi();
6、寄生组合式继承
function SuperType1(name) {
this.name = name;
this.age = 13;
console.log(this);
}
SuperType1.prototype.sayName = function(){
console.log(this.name);
}
function SubType1() {
SuperType1.call(this, "lisi");
}
var obj = Object.create(SuperType1.prototype);
SubType1.prototype = obj;
SubType1.prototype.constructor = SubType1;
var subtype1 = new SubType1();
console.log(subtype1);