Search code examples
javascriptobjectthisprivate-functions

Make object variables be accesible within all "deeper" scope


I'm currently coding a kind of plugin in JS. I've just learnt about objects, and I'm kind of annoyed by the fact that I can't access variables set within the constructor, two or more levels up. Here's what I mean:

    var myConstructor = function()
    {
        this.one = "one";
        this.two = "two";

        this.publicMethod = function()
        {
          console.log("I can access: ", this.one);
          var privateMethod = function()
          {
              console.log("I cannot access var two like this: ", this.two);
          };
          privateMethod();
        };
    };

var myObject =  new myConstructor();
myObject.one = 1;
myObject.two = 2;
myObject.publicMethod();

So, how could I make privateMethod access the variables that are set within the constructor? In the same manner that publicMethod uses this to do so. Is this possible? Thank you very much.


Solution

  • Try this.

     var myConstructor = function()
            {
                this.one = "one";
                this.two = "two";
    
                this.publicMethod = function()
                {
                    // new variable
                    _two = this.two;
                    console.log("I can access: ", this.one);
                    var privateMethod = function()
                    {
                        console.log("I cannot access var two like this: ", _two);
                    };
                    privateMethod();
                };
             };