继承
ECMAScript只支持实现继承,而且其实现继承主要是依靠原型链来实现的。
原型链继承
function Car() {
this.originalColor = 'red'
}
Car.prototype.getCarColor=function name() {
console.log(this.originalColor)
}
function Mazda() {
this.brand = 'mazda'
}
Mazda.prototype = new Car()
let mazda = new Mazda()
mazda.getCarColor()
调用mazda.getCarColor()会经历三个搜索步骤:
1)搜索实例;
2)搜索 Mazda.prototype;
3)搜索 Car.prototype,
搜索过程总是要一环一环地前行到原型链末端才会停下来。
原型链的问题
Mazda.prototype = new Car()
let mazda = new Mazda()
mazda.size.push('middle')
mazda.getCarColor()
let mazda2 = new Mazda()
console.log(mazda2.size)
console.log(mazda.size)
问题一 来自包含引用类型值的原型。我们对 mazda.size 的修改能够通过 mazda2.size 反映出来
问题二 在创建子类型的实例时,不能向超类型的构造函数中传递参数。
构造函数继承
function Animal() {
this.colors = ["red", "blue", "green"];
}
function Dog() {
Animal.call(this)
}
let dog1 = new Dog()
dog1.colors.push('yellow')
console.log(dog1.colors)
let dog2 = new Dog()
console.log(dog2.colors)
通过使用 call()方法(或 apply()方法
也可以) Animal()函数中定义的所有对象初始化代码。
传递参数
function Animal(name) {
this.colors = ["red", "blue", "green"];
this.name = name
}
function Dog() {
Animal.call(this,'zs')
}
let dog1 = new Dog()
console.log(dog1.name)
构造函数继承问题
复用性差
组合继承
组合继承(combination inheritance),有时候也叫做伪经典继承,指的是将原型链和借用构造函数的
技术组合到一块,从而发挥二者之长的一种继承模式。
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)
}
var instance1 = new SubType("Nicholas", 29)
instance1.colors.push("black")
alert(instance1.colors)
instance1.sayName()
instance1.sayAge()
var instance2 = new SubType("Greg", 27)
alert(instance2.colors)
instance2.sayName()
instance2.sayAge()
CombinationInheritanceExample01.htm