Tuesday, October 20, 2015

__proto__

First, let's consider...

var foo = {
   bar: "foo"
}
 
var baz = {
   bar: "baz"
}
 
var qux = Object.create(foo);
 
alert(foo.isPrototypeOf(qux));
alert(baz.isPrototypeOf(qux));
alert(qux.bar);

 
 

this & OBJECT PROTOTYPES, a book on JavaScript by Kyle Simpson, reveals that the means of fudging inheritance above is both easily chain-of-parent-to-child-reverse-engineering-interrogation-friendly and, yes, legitimate as the above will return three alerts reading (for me in Google Chrome):

  1. true
  2. false
  3. foo

 
 

And then, moreover, consider...

var foo = {
   bar: "foo"
}
 
var baz = {
   bar: "baz"
}
 
var qux = Object.create(foo);
 
alert(Object.getPrototypeOf(qux) === foo);
alert(Object.getPrototypeOf(qux) === baz);
alert(qux.bar);

 
 

Alright, both the blob of code above and the blog of code below return the same three alerts. (The only things that vary across all three blobs of code is the first two alerts.) What is below shows off how the wacky __proto__ setting behaves. Kyle cautions that this is not really standardized before ES6 however.

var foo = {
   bar: "foo"
}
 
var baz = {
   bar: "baz"
}
 
var qux = Object.create(foo);
 
alert(qux.__proto__ === foo);
alert(qux.__proto__ === baz);
alert(qux.bar);

 
 

Addendum 10/23/2015: The double underscore is unoffically referred to as a "dunder" in the JavaScript community per Mr. Simpson!

No comments:

Post a Comment