CodePark/ questions / Classes, constructors & fields
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › Classes, constructors & fields

What does this print?

class User {
  id = 1;
  greet() { return "hi"; }
}
const u = new User();
console.log(Object.hasOwn(u, "greet"), Object.hasOwn(u, "id"), typeof User);
false true function

It prints false true function. A class is a constructor function, so typeof User is "function". Methods like greet are put once on User.prototype and shared by every instance. Fields like id = 1 are created on each instance by the constructor, so they are own properties.

"
true true function" is tempting, but greet is not copied onto each object. The instance finds it through the prototype chain.