0

If functions defined inside the class body go automatically to the prototype object, why do I get: TypeError: obj.__proto__.drive is not a function?

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }

  //this is what's happening under the hood 
  // Car.prototype.drive = function(){..}
   drive = function(){
       console.log("driving")
  }
 }

 const obj = new Car("toyota", "1996")

 obj.__proto__.drive()
JethroT
  • 27
  • 5
  • 2
    You're declaring `drive` as a class field (ie: `dirve = ...`), not as a method (ie: `drive(){ ... }`). Class fields are added to the instance and to the prototype. – Nick Parsons Aug 26 '23 at 08:18

1 Answers1

1

As mentioned in a comment you should use method syntax to define a function in a class' prototype:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }

  //this is what's happening under the hood 
  // Car.prototype.drive = function(){..}
   drive(){
       console.log("driving")
  }
 }

 const obj = new Car("toyota", "1996")

 obj.__proto__.drive()
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17