面向对象的程序设计(二)

161 阅读1分钟

继承

ECMAScript只支持实现继承,而且其实现继承主要是依靠原型链来实现的。
原型链继承
function Car() {
    this.originalColor = 'red'  
}
Car.prototype.getCarColor=function name() {
    console.log(this.originalColor)
}
function Mazda() {
    this.brand = 'mazda'
}
//继承car
Mazda.prototype = new Car()
let mazda = new Mazda()
mazda.getCarColor()//red

调用mazda.getCarColor()会经历三个搜索步骤:
1)搜索实例;
2)搜索 Mazda.prototype3)搜索 Car.prototype,
搜索过程总是要一环一环地前行到原型链末端才会停下来。
原型链的问题
//继承car
Mazda.prototype = new Car()
let mazda = new Mazda()
mazda.size.push('middle')
mazda.getCarColor()//red

let mazda2 = new Mazda()
console.log(mazda2.size)//[ 'small', 'big', 'middle' ]
console.log(mazda.size)//[ 'small', 'big', 'middle' ]

问题一 来自包含引用类型值的原型。我们对 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)//[ 'red', 'blue', 'green', 'yellow' ]
let dog2 = new Dog()
console.log(dog2.colors)//[ 'red', 'blue', 'green' ]
通过使用 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)//zs
构造函数继承问题
复用性差
组合继承
组合继承(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);//"red,blue,green,black"
instance1.sayName(); //"Nicholas"; 
instance1.sayAge(); //29 
var instance2 = new SubType("Greg", 27); 
alert(instance2.colors); //"red,blue,green" 
instance2.sayName(); //"Greg"; 
instance2.sayAge(); //27 
CombinationInheritanceExample01.htm