2

I am new to JS (coming from C++). I am learning how objects and inheritance work in JS. So far I have seen expressions of the form Object.<property name> a number of times.

Please correct me if my understanding is wrong. As far as I understand, Object is a function, and can be invoked in new Object() to produce a blank object. Object has many properties. For example, a property with name prototype, as Object is a constructor. But I don't understand why Object has a number of methods such as setPrototypeOf, getPrototypeOf. If one wants to achieve what Object.setPrototypeOf and Object.getPrototypeOf do, why do they have to be implemented as methods of the Object function?

lamc
  • 347
  • 2
  • 5
  • 1
    If the methods were on the prototype, they'd be visible on *all* objects, essentially breaking that property name for all objects. Having a sort of namespace for utility methods makes code more maintainable, because then there aren't any possible property name collisions. – CertainPerformance Oct 01 '22 at 14:11
  • 2
    Javascript doesn't have namespaces (or a standard library), so it uses static methods to treat objects as namespaces. Your question is, in a very real sense, like asking why `std` has so many things in it in C++. You make do with what you have to get what you need. – Jared Smith Oct 01 '22 at 14:16

0 Answers0