ES6 - Class and Inheritance

/**
 * es5:class 对象
 */

function Car(option) {
  this.title = option.title;
  this.lunz = option.lunz;
}

Car.prototype.drive = function () {
  return this.title + " is drive..";
}

const car = new Car({ title: "bmw", lunz: "more than 3." });
console.log(car);
console.log(car.drive());

/**
 * es5:继承
 */

function KIA(option) {
  Car.call(this, option);
  this.color = option.color;
}

KIA.prototype = Object.create(Car.prototype);
KIA.prototype.constructor = KIA;

KIA.prototype.drive = function () {
  return this.title + " is drive, its color is " + this.color;
}

const kia = new KIA({ color: "white", title: "kia", lunz: 'more than 4.' });
console.log(kia.drive());


/**
 * es6 class+继承(extends + super)
 */
class CarES6 {
  constructor({ title, lunz }) {
    this.title = title;
    this.lunz = lunz;
  }
  drive() {
    return this.title + " is drive.. (es6)";
  }
}

const carNew = new CarES6({ title: "bmw", lunz: "more than 3." });
console.log(carNew);

class KIAES6 extends CarES6 {
  constructor(options) {
    super(options);
    this.color = options.color;
  }
}

const kiaNew = new KIAES6({ color: "white", title: "kia", lunz: 'more than 4.' });
console.log(kiaNew);

Guess you like

Origin www.cnblogs.com/tangge/p/12117112.html