Skip to content

Instantly share code, notes, and snippets.

@dgowrie
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save dgowrie/b2a40ea251a4fb422adc to your computer and use it in GitHub Desktop.

Select an option

Save dgowrie/b2a40ea251a4fb422adc to your computer and use it in GitHub Desktop.
Prototypal Inheritance - extending a prototype when creating a 'subclass'
// Demonstrates the side effects of using 'new' to extend a prototype and the reason to use Object.create (with a shim for IE8 support).
//
// It can be a problem to use 'new' when extending a superclass because you're actually running the superclass's constructor.
// Using Object.create() avoids the problem of unintentional side effects from running the superclass constructor.
// see http://www.objectplayground.com/ for details
// Parent class constructor
function Parent() {
alert("side effect!");
}
// Parent class method
Parent.prototype.method = function method() {};
// Child class constructor
function Child() {
this.b = 3.14159
}
// Inherit from the parent class
// OPTION 1: Use Object.create() -- avoids side effect, doesn't work on IE8 <== RECOMMENDED (use Option 3 w/ shim for IE8 if needed)
// Child.prototype = Object.create(Parent.prototype);
// OPTION 2: Use 'new' -- triggers side effect, works on IE8
Child.prototype = new Parent();
// OPTION 3: Use shimmed Object.create() -- avoids side effect, works on IE8
// Child.prototype = myObjectCreate(Parent.prototype);
Child.prototype.constructor = Child;
// Child class method
Child.prototype.method = function method() {
Parent.prototype.method.call(this);
};
// Instantiate
this.instance = new Child();
// Object.create shim, simplified from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill
function myObjectCreate(parent) {
function F(){}
F.prototype = parent;
return new F();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment