JS - 继承

106 阅读1分钟

用class实现继承

class Phone{
  constructor(brand){
    this.brand = brand;
  }
  //父类的成员属性
  call(){
    console.log("我可以打电话!!");
  }
}

class SmartPhone extends Phone {
  constructor(brand, color){
    super(brand);  // Phone.call(this, brand)
    this.color = color;
  }

  photo(){
    console.log("拍照");
  }
  call(){
    console.log('我可以进行视频通话');
  }
}

const xiaomi = new SmartPhone('小米','黑色',);
// console.log(xiaomi);
xiaomi.call();
xiaomi.photo();

ES5的继承

function Phone(brand){
  this.brand = brand;
}
Phone.prototype.call = function(){
  console.log("我可以打电话");
}

//智能手机
function SmartPhone(brand, color){
  Phone.call(this, brand);
  this.color = color;
}
//设置子级构造函数的原型
SmartPhone.prototype.__proto__ = Phone.prototype;   // 或者 SmartPhone.prototype = new Phone();
SmartPhone.prototype.photo = function(){
  console.log("我可以拍照")
}

const chuizi = new SmartPhone('锤子','黑色');
console.log(chuizi);