views:

40

answers:

2

Hi,

I am involved in a web application project at the moment and we are not going to be using a framework.

I am looking for the 'best' javascript inheritance implementation. I have worked with prototypal style classes as follows:

function animal(options) {
    self = this;

    //properties    
    this.name = options.name;

    //events

    this.onXYZ = options.onXYZ;

    //event handlers
    this.handlerOfEvent = function() {
        //do something using 'self' as the 'this' variable
    }
}

animal.prototype.aFunction = function() 
{
     //do something 
}

etc.

I have not used inheritance without a framework (usually use Mootools) but I do understand to a point how it works in Javascript and have seen a fair few implementations.

I wanted to get some feedback on where I could find the best implementation, one that doesn't fiddle with any native types and allows me full access to the ascendant classes' properties and functions.

Any pointers would be greatly appreciated.

Thanks very much for your time.

A: 

You should check the videos from Douglas Crockford about "parasatic inheritance".

Here's a basic example

    var pkg={};//simulating a package
    pkg.ObjA=function (){
    var privateField;//every inner function will have a closure to this field, this is the way to simulate private fields
    var privatefunc=function(){
    //same for private functions
    };
    //use object augmentation to add different fields to the "that" reference
    that.publicMethod=function(){
    //do something
    };
    return that;
    }

    //create two different instance of the object A
    var instance1=pkg.ObjA();
    var instance2=pkg.ObjA();

pkg.ObjB=function(){

//the that of this object is based on the ObjA
var that=pkg.ObjA();

//specialize the that to simulate inheritance
that.newMethod=function(){

}
return that;
}

var child=pkg.ObjB();
Dani Cricco
A: 

There's a method described by (who else) Douglas Crockford that I've been partial to as of late:

var rectangle = function(width, height)
{
    var h = height, w = width;
    var scale = function(s)
    {
        h = h * s;
        w = w * s;
    }

    return { scale: scale };
}

var square = function(width)
{
    var o = rectangle(width, width)
    // Add things to o, if needed
    return o;
}

Not a terribly good example, as nothing is really being extended, but it should get the idea across. In order to instantiate these objects, simply use this:

var newRectangle = rectangle(3, 4);  // 3 by 4 rectangle
var newSquare = square(6);  // 6 by 6 square
Ryan Kinal