Skip to content

Instantly share code, notes, and snippets.

@markhuge
Last active August 29, 2015 14:04
Show Gist options
  • Save markhuge/3519e0ae364462a5c003 to your computer and use it in GitHub Desktop.
Save markhuge/3519e0ae364462a5c003 to your computer and use it in GitHub Desktop.
Javascript prototypal pitfalls
// 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.
*/
// 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