Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript inheritance framework

Is there a small, lightweight solution for javascript class inheritance that will work well on both client and server side (node.js)? I'm not wanting a big library, just something that will allow me to declare a constructor and some methods, then have the ability for a class to inherit that.

like image 937
LordZardeck Avatar asked Feb 23 '12 06:02

LordZardeck


People also ask

What is an inheritance in JavaScript?

Inheritance enables you to define a class that takes all the functionality from a parent class and allows you to add more. Using class inheritance, a class can inherit all the methods and properties of another class. Inheritance is a useful feature that allows code reusability.

Can we do inheritance in JavaScript?

When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype.

How do you handle inheritance in JavaScript?

By calling the super() method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods. Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.


2 Answers

John Resig outlines a simple inheritance framework in about 25 lines of code here. I have seen it used to good effect.

You can use it like this:

var Vehicle = Class.extend({
  init: function(wheels) {
    this.wheels = wheels;
  }
});

var Truck = Vehicle.extend({
  init: function(hp, wheels) {
    this.horsepower = hp;
    this._super(wheels);
  },

  printInfo: function() {
    console.log('I am a truck and I have ' + this.horsepower + ' hp.');
  }
});

var t = new Truck(4, 350);
t.printInfo();
like image 110
jergason Avatar answered Oct 17 '22 03:10

jergason


take a look at https://github.com/ded/klass

like image 32
Cris-O Avatar answered Oct 17 '22 05:10

Cris-O