JS继承

一直以来对js继承这块不是很懂,然后就在高程三上面反复对这块看了几遍,对这几天看的内容作如下整理。

对于OO(Object-Oriented)模式来说,其继承方式有接口继承和实现继承,而对于EcmaScript来说只支持实现继承,而且其实现继承是依靠原型链来实现的。

原型链继承

functionSuperTypes() {
    this.property=true;
}

SuperTypes.prototype.getProperty=function() {
    console.log(this.property);
}

functionSubTypes() {
    this.name='lisp';
}

// 原型链继承
SubTypes.prototype=newSuperTypes();
SubTypes.prototype.getName=function() {
    console.log(this.name);
}

varsub=newSubTypes();
sub.getProperty();// true
sub.getName();// lisp

借用构造函数继承

function SuperTypes(name) {
  this.name = name;
}

function SubTypes(name){
  // 继承了SuperTypes,通过call来实现继承
  SuperTypes.call(this, name);
}

SubTypes.prototype.getName = function() {
  console.log(this.name);
}

var sub = new SubTypes('lisp');
sub.getName(); // lisp

组合继承

function SuperTypes(name) {
  this.name = name;
  this.colors = ['red', 'blue'];
}

SuperTypes.prototype.getColor = function() {
  console.log(this.colors);
}

function SubTypes(name) {
  // 借用构造函数继承
  SuperTypes.call(this, name);
}

// 原型链继承
SubTypes.prototype = new SuperTypes();
SubTypes.prototype.getName = function() {
  console.log(this.name);
}

var sub = new SubTypes('lisp');
sub.colors.push('pink');
sub.getColor(); // ['red', 'blue', 'pink']
sub.getName(); // lisp

原型试继承

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

var person = {
  name: 'lisp',
  age: 22
};

var otherPerson = object(person); // 相当于进行了一次浅复制
console.log(otherPerson.name); // lisp

// Object.create()方法规范化了浅复制
var anotherPerson = Object.create(person);
console.log(anotherPerson.name); // lisp

寄生组合式继承

function inheritPrototype(subType, superType) {
  var property = Object.create(superType.prototype);
  // 将property的指针指向subType
  property.constructor = subType;
  // property赋值给subType的原型
  subType.prototype = property;
}

function SuperTypes(name) {
  this.name = name;
  this.colors = ['red', 'blue'];
}

SuperTypes.prototype.getColor = function() {
  console.log(this.colors);
}

function SubTypes(name) {
  // 借用构造函数继承
  SuperTypes.call(this, name);
}

// 原型链继承
// SubTypes.prototype = new SuperTypes();
inheritPrototype(SubTypes, SuperTypes);

SubTypes.prototype.getName = function() {
  console.log(this.name);
}

var sub = new SubTypes('lisp');
sub.colors.push('pink');
sub.getColor(); // ['red', 'blue', 'pink']
sub.getName(); // lisp

你可能感兴趣的:(JS继承)