如何在javascript中实现继承概念?

时间:2016-12-21 10:28:58

标签: javascript inheritance

我最近开始学习JavaScript。但我没有任何项目经验。最近参加了JavaScript访谈:

他问了一个关于Inheritance的问题:应该是这样的:

我需要一种名为Vehicle和另一种two Methods Like one is Two-Wheeler and another one four-wheeler Method.

的方法

如果我为下面的两个方法

创建实例
var two-wheeler1 = new two-wheeler("Shine","125 kph") ; 

另一个例子如下

var four-wheeler1 = new four-wheller("audi","1000kph");

如果我打印

 two-wheeler1.getWheeles()  //it should print 2 wheels

如果我打印

four-wheeler1.getWheeles() //it Should print 4 Wheels

如何实现这一目标。你能帮助我吗?

2 个答案:

答案 0 :(得分:1)

据推测,面试官和他的公司正在使用现代JS(ES6或TypeScript)进行编程。如果没有,你应该找另一家公司来采访。 ES6为定义类和继承关系提供了很好的干净语法:

class Vehicle {
  constructor(brand, kmp) { 
    this.brand = brand;
    this.kmp = kmp;
  }

  getWheels() { return `${this.nWheels} wheels`; }
}

class TwoWheeler extends Vehicle {
  constructor(brand, kmp) {
    super(brand, kmp);
    this.nWheels = 2;
  }
}

class FourWheeler extends Vehicle {
  constructor(brand, kmp) {
    super(brand, kmp);
    this.nWheels = 4;
  }
}

顺便说一句,在世界其他地方,我们称两轮车为“摩托车”或“摩托车”,四轮车为“汽车”。

答案 1 :(得分:0)

请查看以下代码,以便在JS中获得更好的OOP和继承:

function twoWheeler(brand, kmp) {
   this.brand=brand;
   this.kmp=kmp;
   this.getWheeles=function() {
     return "2 wheels"
   };
   this.getVehicleInfo=function() {
     return "Brand Name: " + this.brand + " Speed: " + this.kmp + " Type: 2   wheeler."
   };
  }

 function fourWheller(brand, kmp){
   this.brand=brand;
   this.kmp=kmp;
   this.getWheeles=function() {
     return "4 wheels"
   };
   this.getVehicleInfo=function() {
      return "Brand Name: " + this.brand + " Speed: " + this.kmp + " Type: 4 wheeler."
    };
  }

  fourWheller.fourWheller= new twoWheeler();
  fourWheller.prototype.constructor=fourWheller;

  var twoWheeler1 = new twoWheeler("Shine","125 kph");
  var fourWheller1 = new fourWheller("Audi","1000kph");

  console.log(twoWheeler1.getWheeles())
  console.log(fourWheller1.getWheeles())

  console.log(twoWheeler1.getVehicleInfo())
  console.log(fourWheller1.getVehicleInfo())