Private static code in JavaScript and inheritance

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

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 trap?

+5
source share
1 answer

First of all, in JavaScript there is no such thing as "private static". What you use here is a simple closure that creates an Instant Call Function Expression .

Your question is not entirely clear, but I think you want to count the created Car instances, and this will not work, because when you create an instance of the subclass, the counter will not increase (problem 1). Instead, the counter only increments once when you define your subclass (Problem 2).

JavaScript , , , . , ( ). , JavaScript (. JavaScript, Backbone, CoffeScript ..), , (IE6-8). :

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

. . , (Java ..). JavaScript , :

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

    // Child class initialization
};

this, . , . , .

+4

All Articles