Skip to content

Instantly share code, notes, and snippets.

@bioball
Created June 17, 2014 19:56
Show Gist options
  • Save bioball/7b2afa239c4eae875601 to your computer and use it in GitHub Desktop.
Save bioball/7b2afa239c4eae875601 to your computer and use it in GitHub Desktop.
Inheritance patterns with constructor functions
// here's a normal JavaScript constructor function
var Block = function(){
this.width = 30;
this.height = 50;
this.otherthing = "whateverelse";
};
// these are class methods that all blocks inherit from
Block.prototype.doThing = function(){
// business logic
};
// here's a subclass
var SquareBlock = function(){
// apply all the properties on the parent onto this child
Block.call(this);
// you can set more properties here
this.bismack = "Biyombo";
// you can also overwrite previously set properies. This will apply to SquareBlock only, and not Block
this.width = 50;
};
// inherit from the same class methods that Block inherits from, and set the .contructor property to refer to SquareBlock (it would default to Block)
SquareBlock.prototype = Object.create(Block.prototype);
SquareBlock.prototype.constructor = SquareBlock;
// you can continue to set methods here that only SquareBlock will inherit from
SquareBlock.prototype.spin = function(){
// do stuff
}
// NOTE: you have to use the `new` keyword to create objects that inherit from these classes. e.g.
var foo = new Block();
var boo = new SquareBlock();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment