Mike
Mike

Reputation: 60751

Javascript, class inheritence, method overriding

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.

Upvotes: 1

Views: 209

Answers (3)

Alex Turpin
Alex Turpin

Reputation: 47776

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();

http://jsfiddle.net/Xeon06/JK5vX/2/

Upvotes: 4

bittersweetryan
bittersweetryan

Reputation: 3443

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

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187004

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.

Upvotes: 0

Related Questions