Alex Rivera | Logout

Is there a "right" way to do inheritance in JavaScript? If so, what is it?

Asked 2008-10-22T03:03:00.980
9

I have been trying to learn how to add testing to existing code -- currently reading reading Working Effectively With Legacy Code. I have been trying to apply some of the principles in JavaScript, and now I'm trying to extract an interface.

In searching for creating interfaces in JavaScript, I can't find a lot -- and what I find about inheritance seems like their are several different ways. (Some people create their own base classes to provide helpful methods to make it easier to do inheritance, some use functions, some use prototypes).

What's the right way? Got a simple example for extracting an interface in JavaScript?

Edit
Report

2 Answers

3

Also check out Dean Edwards' Base.js. You can have a look at it here, the blog post is self-explanatory.

answered 2008-10-22T03:15:19.737
0

Prototype offers its own take on inheritance, from http://www.prototypejs.org/api/class/create:

var Animal = Class.create({
  initialize: function(name, sound) {
    this.name  = name;
    this.sound = sound;
  },

  speak: function() {
    alert(this.name + " says: " + this.sound + "!");
  }
});

// subclassing Animal
var Snake = Class.create(Animal, {
  initialize: function($super, name) {
    $super(name, 'hissssssssss');
  }
});
answered 2008-10-22T13:23:00.307

Your Answer