5

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 ?

1
  • 4
    What does "screws in inheritance" mean? What is the problem you're trying to solve? Commented Jan 23, 2013 at 8:49

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.