JavaScript 类的继承

通过原型链的方式继承

 

通过实例化一个构造函数,使字类的原型指向父类的实例,字类就可以调用到父类的属性和方法

function Parent() {
  this.parentName = '父亲';
  this.getParentName = function () {
    console.log("parent name is: %s", this.parentName);
    return this.parentName;
  }
}
function Child() {
  this.childName = '子类';
  this.getChildName = function () {
    console.log("child name is: %s", this.childName);
    return this.childName;
  }
}
Child.prototype = new Parent();
function yxExtend() {
  let childOne = new Child();
  childOne.getParentName();
  childOne.getChildName();
} 

借用构造函数继承 call/apply函数

call/apply函数 能够改变函数的this指针

function Book(name, color) {
  this.pages = 50;
  this.name = name
  this.color = color;
  this.showBook = function () {
    console.log("name of book: %s", this.name);
    console.log("color of book: %s", this.color);
  }
}
function RedBook(name, color) {
  Book.call(this, name, color);
  this.value = 60;
}
function gzExtend() {
  var redBook = new RedBook("小红书", "红色");
  redBook.showBook();
  console.log("借用构造函数继承 call/apply函数, 打印结果:");
  console.log(redBook);
}

class方式的继承 ES6以后的写法

class+extends+super

继承父实例属性:写在父的constructor中,子使用super访问

继承父实例方法:写在父类体中,子实例对象.方法名

继承静态方法、静态属性:使用static声明,子构造函数.静态方法名/静态属性名

        注:只有在ES6中是这样创建类,给类做继承的

class Car{
  constructor(name, color){
    this.name = name;
    this.color = color;
    this.powertype = "汽油";
    console.log("父类构造器");
  }
  sayCarName(){
    console.log("this car name is: %s", this.name);
  }
  static manufacturer = "默认厂商";
  static carDistinguish(carOne){
    console.log("识别%s是否为 Car", carOne.name);
    console.log(carOne instanceof Car);
    return carOne instanceof Car;
  }
}
class Benz extends Car{
  constructor(name, color, length){
    super(name, color);
    console.log("子类构造器");
    this.length = length;
    this.capacity = 4;  //默认载客量
  }
  static maxSpeed = 200;
  static benzDistinguish(carOne){
    console.log("识别%s是否为 Benz", carOne.name);
    console.log(carOne instanceof Benz);
    return carOne instanceof Benz;
  }
}
function clExtend() {
  
  var one = new Car("比亚迪", "white");
  console.log(one);

  var two = new Benz("奔驰e330", "black");
  two.sayCarName();
  console.log(two);

  console.log("Car.carDistinguish(one) is:");
  Car.carDistinguish(one);

  console.log("Car.carDistinguish(two) is:");
  Car.carDistinguish(two);

  console.log("Benz.carDistinguish(one) is:");
  Benz.benzDistinguish(one);

  console.log("Benz.carDistinguish(two) is:");
  Benz.benzDistinguish(two);
}

控制台的打印结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值