在类减速度之外声明的方法不能被javascript中的子类继承

问题描述 投票:0回答:1
// declared class vehicle
function Vehicle(make,model,year){
  this.make=make
  this.model=model
  this.year=year

}
// 2 - Add a function to the Vehicle prototype called start which returns the string //"VROOM!"
 Vehicle.prototype.start=function(){
  return "VROOM!"
}

// declared child class car
function Car(make,model,year){
  Vehicle.apply(this,arguments)
  this.numWheels=4

}
// assigning the constructor
Car.prototype.constructor=Object.create(Vehicle.constructor)
// changing the pointing of constructor back to car
Car.prototype.constructor=Car;
var sedan=new Car("Tractor", "John Deere", 1999)
console.log(sedan.start()) 
//sedan.start() gives error but if i declare it inside vehicle class does not 
javascript inheritance constructor prototype
1个回答
1
投票

这些代码行没有意义:

// assigning the constructor
Car.prototype.constructor=Object.create(Vehicle.constructor)
// changing the pointing of constructor back to car
Car.prototype.constructor=Car;

它们没有意义,因为对该构造函数进行赋值,然后立即进行another赋值,意味着第一个赋值对任何东西都绝对没有影响。

思考相反,您需要的是:

// assigning the constructor
Car.prototype=Object.create(Vehicle.prototype)
// changing the pointing of constructor back to car
Car.prototype.constructor=Car;
© www.soinside.com 2019 - 2024. All rights reserved.