I've always understood the purpose of a prototype to be a means of
including pre-defined data and behavior in an object. Classes are just a
convenient means of defining those things in a prototype-oriented language,
and from a class POV, the prototype serves the role of the class template.
You did just make me think of something though. In the interest of not
adding another pragma, this feature could, and probably should be limited
to just the prototypes of objects created with the `new` keyword. This
would leave objects created manually alone, preserving the old behavior for
object literals and factory functions.
As for your suggestion, that doesn't work when the element being changed is
on a sub-property of the object.
```js
class Example {
constructor() {
this.x = Object.create(this.x);
}
}
Example.prototype.x = {
y: {
a: 0,
b: 1,
c: 2
}
};
const e1 = new Example();
const e2 = new Example();
console.log(e1.x === e2.x); // false
console.log(e1.x.hasOwnProperty("y")); // false
console.log(e2.x.hasOwnProperty("y")); // false
console.log(e1.x.y.c); // 2
console.log(e2.x.y.c); // 2
e1.x.y.c = 4;
console.log(e1.x.hasOwnProperty("y")); // false
console.log(e2.x.hasOwnProperty("y")); // false
console.log(e1.x.y); // 4
console.log(e2.x.y); // 4
```
On Mon, Nov 26, 2018 at 5:21 PM T.J. Crowder <
[email protected]> wrote:
> From the proposal:
>
> > .,..some of which attempt to obviate the use of the prototype for
> > its intended purpose as the template for an instantiation by new...
>
> I wouldn't say that's "the intended purpose" of a prototype at all. That's
> more a class-centric view of prototypes. Prototypical inheritance is
> *different* from class-based inheritance. Prototypes aren't templates,
> they're living objects.
>
> If you want every instance of a class to have an object property that you
> can modify in a per-instance way, make that object property an object
> backed by a prototype:
>
> ```js
> class Example {
> constructor() {
> this.x = Object.create(this.x);
> }
> }
> Example.prototype.x = {
> y: 0
> };
> const e1 = new Example();
> const e2 = new Example();
> console.log(e1.x === e2.x); // false
> console.log(e1.x.hasOwnProperty("y")); // false
> console.log(e2.x.hasOwnProperty("y")); // false
> console.log(e1.x.y); // 0
> console.log(e2.x.y); // 0
> e1.x.y = 1;
> console.log(e1.x.hasOwnProperty("y")); // true
> console.log(e2.x.hasOwnProperty("y")); // false
> console.log(e1.x.y); // 1
> console.log(e2.x.y); // 0
> ```
>
> Once decorators are up and running, doing this could be a decorator,
> though I submit it's an edge case.
>
> -- T.J. Crowder
>
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss