Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created July 18, 2013 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/6026633 to your computer and use it in GitHub Desktop.
Save WebReflection/6026633 to your computer and use it in GitHub Desktop.
The most obtrusive and dark trick to promote objects inheritance without actually loosing the current one if not at the deepest level. It does not pollute the `Object.prototype`
var promote = function(getPrototypeOf, setPrototypeOf){
// (C) The Evilness
return function(self, Class){
var
promote = typeof Class == 'function' ?
Class.prototype : getPrototypeOf(Class),
current = self,
previous,
next
;
if (promote && !promote.isPrototypeOf(self)) {
do {
previous = current; // {} or latter prototype
current = getPrototypeOf(current); // Object.prototype
next = current && getPrototypeOf(current); // null
} while(next);
setPrototypeOf(previous, promote);
}
return self;
};
}(
Object.getPrototypeOf ||
function(o){return o.__proto__},
Object.setPrototypeOf ||
function(o,p){o.__proto__=p}
);
@WebReflection
Copy link
Author

// example
function A() {}
function B() {}
B.prototype = new A;
function C() {}
var b = new B;
// true, true, false
alert([b instanceof A, b instanceof B, b instanceof C]);
promote(b, C);

// now true, true, true
alert([b instanceof A, b instanceof B, b instanceof C]);

// but this is true too now!!!
alert(A.prototype instanceof C);

promote(b = {}, C);
alert(b instanceof C);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment