Created
May 26, 2011 17:22
-
-
Save honza/993548 to your computer and use it in GitHub Desktop.
Class inheritance in Javascript
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
| var __hasProp = Object.prototype.hasOwnProperty; | |
| var __extends = function(child, parent) { | |
| // copy all properties from parent to child | |
| for (var key in parent) { | |
| if (__hasProp.call(parent, key)) | |
| child[key] = parent[key]; | |
| } | |
| function ctor() { | |
| this.constructor = child; | |
| } | |
| ctor.prototype = parent.prototype; | |
| child.prototype = new ctor; | |
| child.__super__ = parent.prototype; | |
| return child; | |
| }; | |
| // Base class | |
| var Animal = (function() { | |
| Animal.prototype.speak = function() { | |
| console.log("Hi, I'm a " + this.name); | |
| }; | |
| function Animal(name) { | |
| this.name = name; | |
| this.speak(); | |
| } | |
| return Animal; | |
| })(); | |
| // Subclass of Animal | |
| var Dog = (function() { | |
| __extends(Dog, Animal); | |
| // Override the speak method of the base class | |
| Dog.prototype.speak = function() { | |
| console.log("I'm a dog. I can't speak."); | |
| }; | |
| function Dog(name) { | |
| Dog.__super__.constructor.apply(this, arguments); | |
| } | |
| return Dog; | |
| })(); | |
| var dog = new Dog('dog'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment