I'm looking for a simple example of creating a class in Javascript which is then inherited in a subclass. I'm looking in particular for an example of method overridding. I realize Javascript doesn't have the syntax supporting traditional OOP, which seems to be the source of my problem.
-
3Note that in fact JavaScript does not have classes at all. – pimvdb Sep 02 '11 at 20:35
-
you might find it helpful to read these articles: http://www.crockford.com/javascript/inheritance.html and http://ejohn.org/blog/simple-javascript-inheritance/ – scrappedcola Sep 02 '11 at 20:38
-
possible duplicate of [Performing Inheritance in Javascript](http://stackoverflow.com/questions/1586915/performing-inheritance-in-javascript) and [What is "inheritance" in Javascript?](http://stackoverflow.com/questions/5027045/what-is-inheritance-in-javascript). – Felix Kling Sep 02 '11 at 20:41
3 Answers
Here is a simple example showing one of many ways of doing it. I usually use John Resig's system.
function Animal(name) {
this.name = name;
}
Animal.prototype.eat = function() {
alert(this.name + " is eating");
};
Animal.prototype.speak = function() {
alert("Hi my name is " + this.name);
};
function Cow(name) {
this.name = name;
}
Cow.prototype = new Animal();
Cow.prototype.speak = function() {
alert("Moooo");
};
var a = new Animal("John");
a.eat();
a.speak();
var c = new Cow("Mary");
c.eat();
c.speak();

- 46,743
- 23
- 113
- 145
You need to look into the objects prototype, however you won't have traditional sub-classing and inheritance.
I recommend you check out the javascript Garden for at terse explanation: http://bonsaiden.github.com/JavaScript-Garden/#object. Eloquent JavaScript has a more detailed chapter on OOP in JS : http://eloquentjavascript.net/chapter8.html

- 3,383
- 5
- 28
- 42
Javascript doesn't have classes, and it's prototypal inheritance can be a bit odd.
That said, coffee script does it right, and generates a ton of JS scaffold code you would never want to write yourself to make it work.
class Foo
word: -> 'foo'
say: -> alert word()
class Bar extends Foo
word: -> 'bar'
bar = new Bar()
bar.say()
Which compiles into this hairball of JS: https://gist.github.com/1189853
Also, John resign wrote a simple class strategy that might be to your liking. http://ejohn.org/blog/simple-javascript-inheritance/
It turns out you can easily emulate class based semantics in a prototypal language, but not the other way around.

- 178,991
- 47
- 309
- 337