Created
March 12, 2012 13:33
-
-
Save lyuehh/2021953 to your computer and use it in GitHub Desktop.
javascript: Prototypal inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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