3

So I have a bug in some JavaScript code that has been driving me moderately crazy. I've been trying to mimic classical inheritance in JavaScript (I know, I know, half the posts I read on here say not to twist JavaScript into such a framework, but my application needs to have a client-side heirarchy that maps to the inheritance structure of my server-side php code). And mostly, it looks like everything is working. Here's the function I'm using to extend classes:

Function.prototype.inheritsFrom = function(parentClass) {
//:: Ordinary Classes
if (parentClass.constructor == Function) {
    this.prototype             = new parentClass();
    this.prototype.constructor = this;
    this.prototype.parent      = parentClass.prototype;

//:: Abstract Classes
} else {
    this.prototype             = parentClass;
    this.prototype.constructor = this;
    this.prototype.parent      = parentClass;
}
return this;
}

Not my own creation, I found it online, but it works well. The only thing I needed to add was a "super" function to search the prototype chain for parent methods; the parent construct in the aforementioned code doesn't work in every case.

In any case, as I've been ironing out some bugs in my code, I found that one of the methods in my base "class" is accessing/modifying the same variable for all instances created from all of its subclasses. In other words, whenever one instance modifies this variable which should be local to its object context, it in fact modifies some variable that is shared between all instances. Here's the base class:

    function DataManipulatorControl() {
    //|| Private Members ||//

    var that = this;



    //|| Properties ||//

    //|| Root ID
    this.rootID = function(value) {
        if (value !== undefined) {
            if (_root_id !== null) {
                alert('@ ' + _root_id);
                $('#' + _root_id).prop('js_object', null);
            }
            _root_id = value;
            $('#' + _root_id).prop('js_object', this);
        }
        return _root_id;
    }
    var _root_id = null;

    // other properties/methods
}



//|| Class: DataManipulatorContainerControl
function DataManipulatorContainerControl() {
    //|| Private Members ||//

    var that = this;


    // subclass properties/methods
}
DataManipulatorContainerControl.inheritsFrom(DataManipulatorControl);

As I mentioned, when I create new instances of these prototypes, I'm finding that changing the rootID for one instance will change it for all. My first thought was that I forgot a "var" somewhere, and that my function was accessing the global context. That doesn't seem to be the case though, so my next thought is that it's using a variable local to the prototype. That doesn't make much sense to me either though, because variables local to the prototype's constructor call shouldn't be accessible outside of it, unless accessed by a method that already has it in scope. Of course, the rootID() function does have it in scope, but I was under the impression that it would be run using the object context of the invoking object, not the prototype.

So, I'm very confused. Any light that can be shed on this issue would evoke much gratitude.

EDIT: The article provided by PRB describes a solution which cleanly solves this issue - mostly. The article notes that you need to also call the parent class' constructor from within the child class constructor to initialize everything correctly. As a result, all of the methods are created fresh, with their own versions of the parent class local variables in closure.

There does seem to be one shortcoming with this approach (aside from efficiency concerns of duplicating functions in every instance). If one tries to call "overridden" functions from the prototype chain in an attempt at super functionality, this problem will resurface. The prototypes are, as before, instances of a single object, and trying to call their versions of a function will cause them to try to access their instance's local variables.

Still the best solution I've seen though, aside from making all the data public :-).

0

2 Answers 2

2

Using this line is probably the issue:

this.prototype             = new parentClass();

This means that all instances of the function share the same memory blob defined by parentClass(). This is why when you change the value in one, it affects all of them.

3
  • Hmm, I tried removing the "new", setting the function itself to be the prototype, but then it couldn't find the rootID function (which makes sense, because the class function object doesn't get the member functions, an object constructed from calling the class function does). I think with prototypical inheritance, doesn't it use the prototype's members, but the invoking object's context? Nov 17, 2012 at 22:55
  • Here's one explanation for the effect you are seeing : coolpage.com/developer/javascript/…. Haven't read thru all of it - 2 min google. When you set the prototype as a reference to a new object, ever instance is going to share the same reference.
    – PRB
    Nov 17, 2012 at 23:11
  • Hah! That's amazing. The article he cited as incorrect is the very article I got my inheritance function from. Thanks; I'm going to work through that article now :-) Nov 17, 2012 at 23:19
0

Okay, so I've been thinking about it over some dinner, and I think I might have a handle on what's going on. I think I'm confusing variables available to a function due to a changing object context, and variables available to a function because of closures.

As PRB pointed out, my rootID() function always accesses the blob of memory from the instantiated prototype. _root_id is created as a variable local to the constructor for my base class, so when that base class is instantiated to become a prototype, all subclasses using the prototype's function will as a result be reading from/writing to the one variable created in the constructor.

So while that is a valid way to create a prototype, hiding the object's data using variables local to the constructor will not work correctly in subclasses. Rather, I'll need to read from/write to variables in 'this', so that it changes as the object's context changes. If anyone knows of a better way to handle this - one which obeys data hiding, please feel free to comment; a lot of the developers I work with have no qualms about accessing data members directly instead of through accessors. Makes code hard to maintain :-/.

At any rate, thanks PRB for the clarification! ~ Nate

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.