原型链
实现继承主要依靠原型链:其基本思想是利用原型让一个引用类型继承另一个引用类型的属性和方法。
将一个类型的实例赋值给另一个构造函数的原型。
- 优点:
- 1.非常纯粹的继承关系,实例是子类的实例,也是父类的实例
- 2.父类新增原型方法/原型属性,子类都能访问到
- 3.简单,易于实现
- 缺点:
- 1.来自原型对象的所有属性被所有实例共享--->致命
- 2.创建子类实例时,无法向父类构造函数传参--->致命
- 3.要想为子类新增属性和方法,必须要在new Animal()这样的语句之后执行,不能放到构造器中
- 4.无法实现多继承
function SuperType() {
this.property = true;
}
SuperType.prototype.getSuperValue = function () {
return this.property;
};
function SubType() {
this.subproperty = false;
}
//inherit from SuperType
// 原型链继承父类
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function () {
return this.subproperty;
};
var instance = new SubType();
console.log("bb:", instance.getSuperValue()); //bb: true
console.log("aa:", instance.subproperty); //aa: false
// instanceof用于判断一个变量是否某个对象的实例
console.log(instance instanceof Object); //true
console.log(instance instanceof SuperType); //true
console.log(instance instanceof SubType); //true
console.log(Object.prototype.isPrototypeOf(instance)); //true
console.log(SuperType.prototype.isPrototypeOf(instance)); //true
console.log(SubType.prototype.isPrototypeOf(instance)); //true