Re:Understanding JavaScript Objects
by SketchySeaBeast on Friday July 27, 2018 @11:15AM
(#17626553)
To clarify I meant this example:
Was just confused as it seems to be applying class concepts to a function.
[ Parent
| on HN ]
Re:Understanding JavaScript Objects
by kenbellows on Friday July 27, 2018 @12:08PM
(#17626980)
Ah, I see. The special thing here is the `new` keyword. When an object is created using `new myconstructor()`, the following steps occur (among others):
1. create a new empty object; call it `newObj`
2. call the constructor using `newObj` as its `this` context, so that `this.a = 1` is effectively `newObj.a = 1`
3. if the constructor has a `prototype` property defined, invoke `newObj.__proto__ = myconstructor.prototype` to establish the prototype chain on the new object
The critical distinction here is between `constructor.prototype` and `object.__proto__`. For exactly this reason, it bothers me a bit that the article uses `Prototype`, with a capital "P", to mean "the thing that `object.__proto__` points to". This is completely different from the `prototype` (small "p") property of a constructor, which is essentially just a holding place for the `__proto__` property of any objects created by calling this constructor with the `new` keyword.Hopefully that all made sense!
Re:Understanding JavaScript Objects
by WorldMaker on Friday July 27, 2018 @01:42PM
(#17627688)
Note that constructorFunction.prototype predates __proto__ in the official specs (and also `class` notation) and is the oldest bit of object-oriented programming support in JS.
__proto__ on objects was originally a leaky abstraction in a specific browser. It caught on such that other browsers borrowed it, because they unfortunately had to, but the specs and the browsers all consider it deprecated and warn not to use it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
(The standards compliant way to get an object's prototype at runtime is Object.getPrototypeOf(obj), and to change an object's prototype instance at runtime is Object.setPrototypeOf(obj, newPrototype).)
Re:Understanding JavaScript Objects
by kenbellows on Friday July 27, 2018 @03:17PM
(#17628466)
Very good points. And thanks for the note about Object.getPrototypeOf(obj) and Object.setPrototypeOf(obj, newPrototype), I don't think I had ever actually looked that up!
Re:Understanding JavaScript Objects
by SketchySeaBeast on Friday July 27, 2018 @01:19PM
(#17627521)
Yes it did. Thank you!