0

Given:

var car = class Car{
    drive() {}
    park(){}
}

Given car, how can I find what methods this class has, ie "drive" and "park" ? I would have thought they were on

car.prototype

It's true that

car.prototype.drive

returns the method and

car.prototype.hasOwnProperty("drive") => true

but

for(let prop_name in car.prototype){
    console.log(prop_name)
}

prints nothing.

user1343035
  • 245
  • 3
  • 13

1 Answers1

0

The property is not enumerable (car.prototype.propertyIsEnumerable("drive") === false), therefore it doesn't show it. See MDN.

The for...in statement iterates over the enumerable properties of an object, in original insertion order

Otherwise you are correct, the function is on the prototype.

Note that this is not and instance method. An instance method exists once per instance, as the name already implies. You can generate instance methods e.g. with

class car {
  constructor() {
    this.instanceFunc = () => {};
  }
}

Note here that explicitly new car().instanceFunc !== new car().instanceFunc

ASDFGerte
  • 4,695
  • 6
  • 16
  • 33
  • ‘An instance method exists once per instance’ Not exactly. In JavaScript, *instance methods* means accessible from an instance, and *static methods* means accessible from a class. Instance methods can be shared by all instances (if you declare them on the instances’ prototype, that is as *methods* in a `class` body) or specific to each instance (if you declare them on the instances, that is as *fields* in a `class` body or as properties of `this` in methods of a `class` body). Check out the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_Classes). – Géry Ogam Apr 02 '23 at 11:25
  • For instance, with `class A {x; static y; f() {} static g() {} constructor() {this.z = 0}}`, you get: `Object.getOwnPropertyNames(A)` returns `['length', 'name', 'prototype', 'g', 'y']`, `Object.getOwnPropertyNames(A.prototype)` returns `['constructor', 'f']`, and `Object.getOwnPropertyNames(new A)` returns `['x', 'z']`. – Géry Ogam Apr 02 '23 at 11:44