Reason
Reason

Reputation: 1430

Private variables and access to parent object

I want a main object M containing a sub-object S which has some method E which has a private variable P. I also want the method E to have access to M via another variable V. For the private variables I'm doing this:

M.S = function () {
    var P,
        V; // how to set V to M?

    return {
        E: function () {
            // stuff goes here
        }
    }
}();

One solution I came up with was to remove the () at the last line, and then calling the anonymous S-creating function as a method of M. this solves the problem, but I'm thinking there might be a more elegant way to go about it.

M.S = function () {
    var P,
        V = this;

    return {
        E: function () {
            // stuff goes here
        }
    }
};
M.S = M.S()

Mostly I need to know what is good practice for this, since I'm new to private variables in Javascript.

Upvotes: 1

Views: 310

Answers (2)

Rob W
Rob W

Reputation: 348972

A pretty straightforward method to do this is:

M.S = function (V) { // <-- V is declared locally
    var P;

    return {
        E: function () {
            // stuff goes here
        }
    };
}(M);

V is locally declared through the formal parameter. M's reference is assigned to V, through function(V){...}(M);.

Even when M is redeclared at a later point, V will still point to the right object.

Upvotes: 3

dfsq
dfsq

Reputation: 193261

What about this? You invoke S in context of M:

M.S = function () {
    var P,
        V = this; // how to set V to M?

    return {
        E: function () {
            // stuff goes here
            // you can refer M via V reference
        }
    }
}.call(M);

Upvotes: 1

Related Questions