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的继承有6种方式,大致总结一下它们各自的优缺点,以及它们之间的关系。 1.原型链 js的继承机制不同...
    空_城__阅读 802评论 0 11
  • 大多OO语言都支持两种继承方式: 接口继承和实现继承 ,而ECMAScript中无法实现接口继承,ECMAScri...
    常连海阅读 110评论 0 1
  • 秋水长天不一色阅读 162评论 0 1
  • 【目录】 这是《落叶》文集里第19片落叶,希望你能喜欢,不为别的,只为这份坚持。 9月初的时候,我净值大约在86....
    秋之川阅读 383评论 0 0
  • 可能由于情人节才过的原因,近日老是想起峨眉山金顶上累累的同心锁。看着那铁链上沉的不能再沉的同心锁,有的泛着金属的...
    绿蚁红泥阅读 571评论 0 0