Created
July 10, 2014 05:27
-
-
Save adohe-zz/2f453c0f6f6ab1e0b785 to your computer and use it in GitHub Desktop.
JavaScript prototype chain thought
This file contains hidden or 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
| function getProperty (obj, prop) { | |
| if (obj.hasOwnProperty(prop)) { | |
| return obj[prop]; | |
| } | |
| if (obj.__proto__ !== null) { | |
| return getProperty(obj.__proto__, prop); | |
| } | |
| return undefined; | |
| } | |
| var sayTwo = { | |
| you: 'you', | |
| me: 'me', | |
| print: function () { | |
| console.log(this.you + this.me); | |
| } | |
| }; | |
| var p = { | |
| you: 'beep', | |
| me: 'boop', | |
| '__proto__': sayTwo | |
| }; | |
| p.print(); | |
| var say = function (word) { | |
| this.word = word; | |
| this.name = "David Zhang"; | |
| } | |
| var say1 = new say('beep'); | |
| var say2 = new say('boop'); | |
| say1.name = 'Jeff'; | |
| console.log(say2.name); | |
| Object.create = function (parent) { | |
| function F () {} | |
| F.prototype = parent; | |
| return new F(); | |
| } | |
| var s = Object.create(sayTwo); | |
| s.print(); | |
| var P = new function () {} | |
| console.log(P.prototype); | |
| P.prototype.name = "beep"; | |
| var a = new P; | |
| console.log(a.name); | |
| console.log(a.__proto__ === P.prototype); | |
| a.__proto__.name = "boop"; | |
| console.log(P.prototype.name); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment