Last active
August 29, 2015 14:04
-
-
Save markhuge/3519e0ae364462a5c003 to your computer and use it in GitHub Desktop.
Javascript prototypal pitfalls
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
// Pseudoclassical class pattern | |
// Constructor | |
function myThing() { | |
// under the hood 'this' is mapped to a new object | |
// created from myThing's prototype and NOT to myThing | |
this.name = "myThing"; | |
} | |
// augment our prototype with a new method | |
myThing.prototype.someMethod = | |
function (a,b) { return "you called someMethod"; }; | |
// augment our prototype with another new method | |
myThing.prototype.otherMethod = | |
function () { return "you called otherMethod"; }; | |
// Create a new object using myThing's prototype | |
var newThing = new myThing(); | |
/* | |
This creates an interesting problem. If you run myThing() | |
without using 'new', the global object is mapped to 'this'. | |
Whatever follows 'this.' is replaced in the global scope | |
and myThing() returns the global object instead of a new | |
instance. | |
*/ |
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
// Pseudoclassical Inheritance Pattern | |
// Constructor | |
function yourThing() { | |
this.name = "yourThing" | |
} | |
// Here we need to use an INSTANCE of the parent prototype | |
yourThing.prototype = new myThing() // WTF right? | |
// Augment our prototype with a new method | |
yourThing.prototype.yourMethod = | |
function () { return "you called yourMethod"; }; | |
foo = new yourtThing() | |
// foo.name returns "yourThing" ...but foo.constructor returns myThing() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment