2

I'm working on a JavaScript project, and was just wondering why an object instance doesn't inherit the assign() and other methods, rather than having to call the superclass (superobject?) Object method.

Why is it Object.assign() rather than this.assign() (for objects)?

аlex
  • 5,426
  • 1
  • 29
  • 38
  • 3
    Because every constructor in the millions of lines of legacy code creates objects that would have to be able to find those on the base `Object.prototype` object, and the chances of collision with common names like "assign" would be pretty great. (Even non-legacy brand-new code would have to work around those symbols.) – Pointy Apr 04 '19 at 12:57
  • How do you create your object? -> Prototypal Inheritance – nologin Apr 04 '19 at 12:59
  • That's just my supposition however; you'd have to poll the language committee or look for old email threads etc. – Pointy Apr 04 '19 at 13:00
  • 1
    I think that there is a "cost" for adding another method to each one of the `Object`'s instances rather than having it stored in one place, unlike `toString` or `valueOf` that are been added to each one of the instances. – Shahar Shokrani Apr 04 '19 at 13:06

1 Answers1

0

Because of the way inheritance works in JavaScript. Quoting from

JavaScript For Beginners: the ‘new’ operator

When you use new, four things happen:

  1. It creates a new, empty object.
  2. It binds this to our newly created object.
  3. It adds a property onto our newly created object called “proto” which points to the constructor function’s prototype object.
  4. It adds a return this to the end of the function, so that the object that is created is returned from the function.

So the super object method's aren't copied to the new object. They're accessible through the newly created object's prototype.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73