Search code examples
javascriptinheritanceprivate-members

Simple JavaScript Inheritance with instance variables


I'm trying to use: Simple Javascript Inheritance by John Resig

What I find really limited is the fact that the variables are not private to an instance of the object. This simple fact is one of the key factor for which a person would choose to adopt this kind of approach.

I've seen in the comments in the linked page that someone is suggesting the following:

init: function() {
  // Private var
  var _div = $( div );
  // Priviledged method accesses private var
  this.getDiv = function () { return _div; }
  this.setDiv = function (div) { _div = div; }
  // other initialization stuff
}

I have some doubts about this approach:

  1. In the class I'm declaring, will I need to access this variables always through setter and getter?
  2. How can I use this variables in the definition of inner functions?

Let's say for example:

node.append("title").text(function(d) { /* use private variable */ });

Has someone overcame this limitation?

Thanks and best regards

Sergio


Solution

  • first of all thank you Alex for your kind reply. It took me some time to digest all the things you though me.

    I want to answer my onw question though cause I had specific needs and I don't feel like the question was well posed at first.

    Let's add as well that data isolation is not a concern, since in my application I will create instances of a hierarchy dinamically and invoke a method on them. People will eventually need to provide new implementations of the "root" object and my application will use them when needed.

    I actually made some tests and made sure that the variables declared in the init method like this:

    this._instanceVar
    

    are actually owned by the instance itself. In other methods declared in the class I can access them by simply referencing them like that.

    For the second point instead, I found a solution which doesn't appeal me completely but to which I will stick. The point is to copy this into a variable local with respect to the closure of the method I'm declaring. This variable will allow me to pass things to inner functions:

    for example:

    var Person = Class.extend({
        init: function() {
            this._name;
        },
        printNameOnClick: function() {
            var thiz = this;
            document.getElementById('nameDiv').addEventListener("click", function() {
                document.getElementById('nameDiv').innerHTML = thiz.name;
            });
        }
    }
    

    Or whaterver.

    The whole point of this though it was to be able to instanciate dinamically an instance of a particular object on which to call a single method. A hierarchical model allows me to be sure that at list the function in the top class will be invoked.

    Best regards,

    Sergio