Skip to content

Instantly share code, notes, and snippets.

@honza
Created May 26, 2011 17:22
Show Gist options
  • Select an option

  • Save honza/993548 to your computer and use it in GitHub Desktop.

Select an option

Save honza/993548 to your computer and use it in GitHub Desktop.
Class inheritance in Javascript
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