N. Taylor Mullen
N. Taylor Mullen

Reputation: 18301

Most efficient way to use inheritance in this example?

So I've been messing around with some JavaScript inheritance techniques and here's one case in which I'm trying to derive a strong solution.

Here's a simple example: http://jsfiddle.net/JgrYu/

The Issue: Logically we'd expect the two div's to be both 0's. But since we're just newing the extended class we don't re-generate our "c" variable.

A potential fix for this is to use Functional inheritance: http://jsfiddle.net/h8xtz/

function mybase() {
    var that = {};
    var c = 0;

    that.hi = function() {
        var ele = $('<div></div>');
        ele.html(c++);
        $('body').append(ele);
    }

    return that;
}

function myextended() {
    var that = mybase();

    that.hi();

    return that;
}

myextended.prototype = new mybase();

$(document).ready(function() {
    var a = myextended();
    var b = myextended();
})​

However the issue with this is that we clutter the global namespace and each object duplicates the functional properties when in reality we just want duplication of the private variables.

So, what I'm looking for is a better approach than functional inheritance to solve this issue. I've thought about making a psuedo classical inheritance structure where I separate the private and public variables/functions but I haven't been able to come up with a version with less overhead than the functional inheritance.

Upvotes: 0

Views: 95

Answers (2)

Bergi
Bergi

Reputation: 664886

If you want to create a new set of private variables for each object, you will need to call the parent's constructor from the child's one. And don't use a instance of the parent as the prototype object for the child, but just an object that inherits from the parent's prototype object. This can be done with Object.create:

function myextended() {
    mybase.call(this); // apply the parent's constructor on the new object
    this.hi();
}

myextended.prototype = Object.create(mybase.prototype);

(Demo)

Upvotes: 1

Briguy37
Briguy37

Reputation: 8402

How about making the variable a part of the prototype:

function mybase() {

    this.hi = function() {
        var ele = $('<div></div>');
        ele.html(this.c++);
        $('body').append(ele);
    }
}

mybase.prototype.c = 0;

Here's the updated fiddle.

Note: Alternatively you could initialize this.c when declaring mybase.

Upvotes: 0

Related Questions