JavaScript 中的继承

原型链

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
}
var instance = new SubType()  
alert(instance.getSuperValue())  

借用构造函数

function SuperType() {  
  this.color = ['red', 'blue', 'green']
}
function Subtype() {  
  SuperType.call(this)
}
var instance1 = new SubType()  
instance1.color.push('black')  
alert(instance.color)  
var instance2 = new SubType()  
alert(instance2.color)  

组合继承

function SuperType(name) {  
  this.name = name
  this.color = ['red', 'blue', 'green']
}
SuperType.prototype.sayName = function() {  
  alert(this.name)
}
function SubType(name, age) {  
  Subtype.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()  

原型式继承

function object(o) {  
  function F() {}
  F.prototype = o
  return new F()
}

寄生式继承

function createAnother(original) {  
  var clone = object(original)
  clone.sayHi = function() {
    alert('hi')
  }
  return clone
}

寄生组合式继承

通过构造函数来继承属性,通过原型链的混成形式来继承方法

function inheritPrototype(subType, superType) {  
  var prototype = object(superType.prototype)
  prototype.constructor = subType
  subType.prototype = prototype
}
function SuperType(name) {  
  this.name = name
  this.color = ['red', 'blue', 'green']
}
SuperType.prototype.sayName = function() {  
  alert(this.name)
}
function SubType(name, age) {  
  SuperType.call(this, name)
  this.age = age
}
inheritPrototype(SubType, SuperType)  
SubType.prototype.sayAge = function() {  
  alert(this.age)
}

nodejs 实现

var inherits = function(ctor, superCtor) {  
  ctor.super_ = superCtor
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  })
}
const EventEmitter = require('events')  
function MyStream() {  
  EventEmitter.call(this)
}
inherits(MyStream, EventEmitter)  
MySteam.prototype.write = function(data) {  
  this.emit('data', data)
}
const steam = new MySteam()  

yofineliu

Read more posts by this author.