开发者

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 metho开发者_StackOverflow中文版d overridding. I realize Javascript doesn't have the syntax supporting traditional OOP, which seems to be the source of my problem.


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/


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜