-
原型链继承
function SuperType() {
this.property = true
}
SuperType.prototype.getSuperVal = function() {
return this.property
}
function SubType() {
this.subproperty = false
}
SubType.prototype = new SuperType()
SubType.prototype.getSubVal = function() {
return this.subproperty
}
SubType.prototype.getSuperVal = function() {
return false
}
let instance = new SubType()
console.log(instance.getSuperVal())
function SuperType() {
this.color = ['red', 'blue', 'yellow']
}
function SubType() {
}
SubType.prototype = new SuperType()
let instance1 = new SubType()
instance1.color.push('pink')
let instance2 = new SubType()
console.log(instance2.color)
-
构造函数继承
function SuperType(name) {
this.name = name
this.color = ['red', 'blue', 'yellow']
console.log(name)
this.fn = function(){
console.log('fn is call')
}
}
function SubType() {
SuperType.call(this, 'nick')
}
var instance3 = new SubType()
instance3.color.push('black')
console.log(instance3.color)
var instance4 = new SubType()
console.log(instance4.color)
-
组合继承
function SuperType(name) {
this.name = name
this.color = ['red', 'blue']
}
SuperType.prototype.sayName = function() {
console.log('supertype->', this.name)
return 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(){
console.log('subtype->', this.age)
return this.age
}
var instance5 = new SubType('john', 30)
instance5.color.push('green')
console.log(instance5, instance5.sayName(), instance5.sayAge())
var instance6 = new SubType('mary', 26)
instance6.color.push('orange')
console.log(instance6, instance6.sayName(), instance6.sayAge())
-
原型式继承
function object(o) {
function F() {}
F.prototype = o
return new F()
}
var person = {
name: 'dalin',
friends: ['kiol', 'mary']
}
var person1 = object(person)
person1.name = 'jekon'
person1.friends.push('tina')
var person2 = object(person)
person2.name = 'erika'
person2.friends.push('luna')
console.log(person, person1, person2)
-
寄生式继承
function createAnother(original) {
var clone = Object.create(original)
clone.sayHi = function() {
console.log('hi')
}
return clone
}
var personAnother = {
name: 'yelia',
friends: ['bill', 'verlia']
}
var personObj = createAnother(personAnother)
personObj.sayHi()
-
寄生组合式继承
function inheritPrototype(subType, superType) {
var prototype = Object.create(superType.prototype)
prototype.constructor = subType
subType.prototype = prototype
}
function SuperType(name) {
this.name = name
this.colors = ['red', 'blue']
}
SuperType.prototype.sayName = function() {
console.log(this.name)
return this.name
}
function SubType(name, age) {
SuperType.call(this, name)
this.age = age
}
inheritPrototype(SubType, SuperType)
SubType.prototype.sayAge = function() {
console.log(this.age)
return this.age
}
var instance7 = new SubType('lily', 28)
console.log(instance7, instance7.sayName(), instance7.sayAge())