Skip to content

Instantly share code, notes, and snippets.

@lyuehh
Created March 12, 2012 13:33
Show Gist options
  • Save lyuehh/2021953 to your computer and use it in GitHub Desktop.
Save lyuehh/2021953 to your computer and use it in GitHub Desktop.
javascript: Prototypal inheritance
Object.beget = (function(Function){
return function(Object){
Function.prototype = Object;
return new Function;
}
})(function(){});
/*
It's a killer! Pity how almost no one uses it.
It allows you to "beget" new instances of any object, extend them, while maintaining a (live) prototypical inheritance link to their other properties. Example:
*/
var A = {
foo : 'greetings'
};
var B = Object.beget(A);
alert(B.foo); // 'greetings'
// changes and additionns to A are reflected in B
A.foo = 'hello';
alert(B.foo); // 'hello'
A.bar = 'world';
alert(B.bar); // 'world'
// ...but not the other way around
B.foo = 'wazzap';
alert(A.foo); // 'hello'
B.bar = 'universe';
alert(A.bar); // 'world'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment