Understanding "Prototypes" in JavaScript
yehudakatz.com
yehudakatz.com
{__proto__: o}
People seem to think that this is functionality that was lacking from JavaScript; many of these same people have some inexplicable distaste for the (non-standard) `__proto__` property. What gives?(Okay, technically it's {__proto__: o, constructor: function F() {}}...)
More knowledgable people than myself discuss it on this es-discuss thread: http://www.mail-archive.com/es-discuss@mozilla.org/msg06142....
There is a Harmony proposal for a "set prototype of operator" that would solve this problem; instead of writing:
var newObj = {__proto__: OldObject, id: 5}
You would write: var newObj = OldObject <| { id: 5 }
Detailed here:
http://wiki.ecmascript.org/doku.php?id=harmony:proto_operato...I know people don't use mutable __proto__ for anything useful, but it does enable some neat tricks. Personally I wish implementors would embrace it and optimize for it rather than trying to make it go away.
As for the "prototype for" operator... that's disgusting.
It's easy to see how it applies locally to descendants of the original object, such as here:
var person = Object.create(null);
defineProperty(person, 'fullName', function() {
return this.firstName + ' ' + this.lastName;
});
where neither fullname nor person even have those properties, but their descendents do.var man = fromPrototype(person, { sex: "male" });
After this code runs, we have a reference to a function (man) inside which we declare an object (newObject) for which we define the new property (sex). That means we can now call newObject.sex
But later he's calling that property on the function itself : jeremy.sex
How is this possible?
return newObject;
'man' and 'jeremy' are objects, not functions.