js继承

2017-07-13  本文已影响0人  小王啊_

原型继承

function superType() {
  this.issuper = true;
}

superType.prototype.superFn = function () {
  console.log('super function');
}

function subType() {
  this.issub = true
}

subType.prototype = new superType();

subType.prototype.subFn = function () {
  console.log('sub funciton');
}

借用构造函数

function superType() {
  this.issuper = true;
}

superType.prototype.superFn = function () {
  console.log('super function');
}

function subType() {
  superType.call(this);
  this.issub = true
}

subType.prototype.subFn = function () {
  console.log('sub funciton');
}

组合继承

function superType() {
  this.issuper = true;
}

superType.prototype.superFn = function () {
  console.log('super function');
}

function subType() {
  superType.call(this);
  this.issub = true
}

subType.prototype = new superType();

subType.prototype.subFn = function () {
  console.log('sub funciton');
}

原型式继承

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

ECMAScript5 中已经规范这种继承方式:

Object.create();

寄生式继承


function createAnotherObj(original) {
  var clone = object(original);
  clone.sayHi = function () {
    console.log('hi');
  }
  return clone;
}
上一篇下一篇

猜你喜欢

热点阅读