- 原型链继承 ```javascript function SuperType(){ this.property = true; }
SupeType.prototype.getSuperValue = function(){ return this.property; }
function SubType(){ this.subProperty = false; }
SubType.prototype = new SuperType(); SubType.prototype.getSubValue = function(){ return this.subproperty; }
弊端: 父类构造函数初始化的属性在原型链上, 对父类属性的更改将会印象到每一个实例。 父类构造函数初始化的属性应该是实例化对象的属性
如以下对colors的修改将会影响两个实例: function SuperType(){ this.colors = [“red”, “blue”, “green”]; } function SubType(){}
SubType.prototype = new SuperType();
var instance1 = new SubType(); instance1.colors.push(“black”); alert(instance1.colors); //“red,blue,green,black”
var instance2 = new SubType(); alert(instance2.colors); //“red,blue,green,black”
2. 构造函数继承
```javascript
function SuperType(){
this.colors = ["red", "green", "blue"];
}
function SubType() {
SuperType.call(this);
}
解决了原型链继承的弊端(父类构造函数初始化的属性在原型链上, 对父类属性的更改将会印象到每一个实例。)
弊端:
只能继承父类的属性和方法(调用父类构造函数),不能继承原型属性和方法
由于每个实例都会调用父类构造函数,所以每个子类都有父类的实例属性和对象。影响性能。
- 组合继承 ```javascript function SuperType(name){ this.name = name; this.colors = [‘red’, ‘blue’, ‘green’]; }
SuperType.prototype.sayName = function(){ alert(this.name); }
function SubType(name, age){ SuperType.call(this, name) this.age = age; }
SubType.prototype = new SuperType() SubType.prototype.constructor = SubType SubType.prototype.sayAge = function(){ alert(this.age) }
弊端: 由于每个实例都会调用父类构造函数,所以每个子类都有父类的实例属性和对象。影响性能。
4. 原型式继承
```javascript
function object(obj) {
function F(){}
F.prototype = obj;
return new F();
}
var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = object(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");
var yetAnotherPerson = object(person);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");
alert(person.friends); //"Shelby,Court,Van,Rob,Barbie"
弊端:
多个实例对象原型引用相同, 存在篡改的可能
无法传递参数
寄生式继承
function createAnother(original) {
let clone = object(original)
clone.sayHi = function() {
alert("hi")
}
return clone
}
主要是增强了函数
弊端同原型式继承
寄生组合式继承(最成熟的方法) ```javascript function inheritPrototype(subtype, supertype){ let prototype = Object.create(supertype.prototype); prototype.constructor = subtype; subtype.prototype = prototype; }
function SuperType(name) { this.name = name; this.colors = [‘red’, ‘blue’, ‘green’]; }
SuperType.prototype.sayName = function() { alert(this.name) }
function SubType(age) { SuperType.call(this, name); this.age = age; }
inheritPrototype(SubType, SuperType); SubType.prototype.sayAge = function() { alert(this.age) }
7. ES6类继承extends
```javascript
// 继承核心代码
function _inherites(subType, superType) {
subType.prototype = Object.create(superType && superType.prototype, {
constructor: {
value: subType,
enumerable: false,
writable: true,
configurable: true,
}
})
if(superType) {
Object.setPrototypeOf
? Object.setPrototypeOf(subType, superType)
: subType.__proto__ = superType
}
}