Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private static in JavaScript and Inheritance

Tags:

javascript

I understand how private static mechanism works in javascript; but that screws in inheritance. For example:

var Car = (function() {
    var priv_static_count = 0;
    return function() {
        priv_static_count = priv_static_count + 1;   
    }
})();
var SedanCar = function () {};
SedanCar.prototype = new Car();
SedanCar.prototype.constructor = SedanCar;

Is there any way to avoid this pitfall ?

like image 791
John Smith Avatar asked Oct 06 '22 06:10

John Smith


1 Answers

First of all, there's no such thing as "private static" in JavaScript. What you use here is a simple closure, which is created by a Immediately-Invoked Function Expression.

Your question is not quite clear, but I guess you want to count the Car instances that were created, and it doesn't work, because when you instantiate the subclass the counter won't increment (problem 1). Instead, the counter is incremented only once, when you define your subclass (problem 2).

Since JavaScript has a prototype based inheritance model, you have to create an object that can be used as prototype. But I suggest you to do it without calling the parent class' constructor (this will solve the second part of the problem). This is a very common pattern used everywhere in the JavaScript world (see Simple JavaScript Inheritance, Backbone, CoffeScript, etc.), and it is very simple to implement if you don't need to support very old browsers (IE6-8). It goes like this:

SedanCar.prototype = Object.create(Car.prototype)

Now the first part of the problem is quite simple to fix. Just call the parent constructor every time the child is instantiated. This is also a quite good pattern, and it is built into many other languages (Java, etc.). In JavaScript, you will have to do it manually, like this:

var SedanCar = function () {
    // Parent class initialization
    Car.call(this /*, and, other, arguments, to, the, parent, constructor */)

    // Child class initialization
};

This will call the parent constructor with this bound to the newly created object. The parent constructor does the initialization, and then the child does it's share of the work. In your example, the parent will increment the counter as you would expect.

like image 128
molnarg Avatar answered Oct 07 '22 20:10

molnarg