[toc]
function SuperType(){
this.property = true
}
SuperType.prototype.getSuperValue = function(){
return this.property
}
function SubType(){
this.subProperty = false
}
SubType.prototype = new SuperType()
SubType.prototype.getSubValue = function(){
return this.subProperty
}
const ins = new SubType()
console.log(ins.getSuperValue()) // true
function SuperType(){
this.colors = ['red', 'blue', 'green']
}
function SubType(){
// 继承了 SuperType
SuperType.call(this)
}
const ins1 = new SubType()
ins1.colors.push('black')
console.log(ins1.colors) // ['red', 'blue', 'green', 'black']
const ins2 = new SubType()
console.log(ins2.colors) // ['red', 'blue', 'green']
function SuperType(name){
this.name = name
this.colors = ['red', 'blue', 'green']
}
SuperType.prototype.sayName = function(){
console.log(this.name)
}
function SubType(name, age){
// 继承了 SuperType
SuperType.call(this, name)
this.age = age
}
SubType.prototype = new SuperType()
SubType.prototype.sayAge = function(){
console.log(this.age)
}
const ins1 = new SubType('tom', 23)
ins1.colors.push('black')
console.log(ins1.colors) // ['red', 'blue', 'green', 'black']
ins1.sayName() // tom
ins1.sayAge() // 23
const ins2 = new SubType('jack', 24)
console.log(ins2.colors) // ['red', 'blue', 'green']
ins2.sayName() // jack
ins2.sayAge() // 24
function object(obj){
function F(){}
F.prototype = obj
return new F()
}
function createAnother(origin){
const clone = object(origin)
clone.sayHi = function(){
console.log('hi')
}
return clone
}
基本思想: 通过构造函数来继承属性,通过原型链的混成形式来继承方法
function SuperType(name){
this.name = name
this.colors = ['red', 'blue', 'green']
}
SuperType.prototype.sayName = function(){
console.log(this.name)
}
function SubType(name, age){
SuperType.call(this, name)
this.age = age
}
SubType.prototype = new SuperType()
SubType.prototype.constructor = Subtype