JS继承

205 阅读1分钟

什么是继承:

  A对象通过继承 B 对象,就能直接拥有 B 对象的所有属性和方法。


原型链继承

  关键点:子类型的原型为父类型的一个实例对象,子类继承父类的属性和方法是将父类的私有属性和公有方法都作为自己的公有属性和方法

// 父类
function Staff() {    
 this.company = 'tianchuang';
 this.list = [];
}
// 父类的原型
Staff.prototype.getComName = function() {
return this.company;
};

// 子类
   function Coder(name, skill) {
     this.name = name;
     this.skill = skill;
   }

// 继承 Staff
   Coder.prototype = new Staff();

// 因为子类原型的指向已经变了,所以需要把子类原型的contructor指向子类本身
   Coder.prototype.constructor = Coder;

// 给子类原型添加属性
   Coder.prototype.getInfo = function() {
     return {
       name: this.name,
      skill: this.skill
     };
   };

   let coder = new Coder('小明', 'javascript');

   coder.getInfo(); // {name: '小明', skill: 'javascript'}
   coder.getComName(); // 'tianchuang'

class extend 继承

ES6 中有了类的概念,可以通过 class 声明一个类,通过 extends 关键字来实现继承关系。

class Parent {
  constructor(name) {
    this.name = name;
  }
  static say() {
    return 'hello';
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name); // 调用父类的 constructor(name)
    this.age = age;
  }
}

var child1 = new Child('kevin', '18');

console.log(child1);