Skip to content

Instantly share code, notes, and snippets.

@constantology
Last active October 14, 2015 01:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save constantology/4286804 to your computer and use it in GitHub Desktop.
Save constantology/4286804 to your computer and use it in GitHub Desktop.
An explanation of `__proto__` using an example and a `__proto__` "polyfill" for MSIE 9 & 10.
function Collection() {
this.push.apply( this, arguments );
}
Collection.prototype = [];
Collection.prototype.push = function( item ) { // we need to wrap this.push in a function or we'll get a recursion error from
if ( arguments.length > 1 ) { // the arguments.length always being > 1 since the Array index is passed to the iterator
this.slice.call( arguments ).map( function( val ) { this.push( val ); }, this );
return this.length;
}
console.log( 'pushing: ', item );
var proto_collection = this.__proto__, // this is the prototype of the class we're in, i.e. Collection.prototype
proto_array = proto_collection.__proto__; // this is the super class, i.e. the new Array we assigned to Collection.prototype on line 5.
return proto_array.call( this, item );
}
// this will make __proto__ available in MSIE 9 & 10
;!function( item ) {
if ( ( !( '__proto__' in item ) ) { // NOTE: Never put the `writable` property in an accessor descriptor
Object.defineProperty( Object.prototype, '__proto__', { // not even as `false` as it b0rks the goddamn definition
configurable : true, // see: https://plus.google.com/117400647045355298632/posts/YTX1wMry8M2
enumerable : false,
get : function() {
return Object.getPrototypeOf( this );
}
} );
}
}( {} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment