patrick
patrick

Reputation: 9752

externally setting variables that should be accessible within an object

Ok, so I know through closure I can do something like this:

var x,
    obj = {
            init: function() {
            x = 123;
          },

          func: function() {
            return x;
          }

    };

obj.init();
obj.func();
==> 123

However, I would like to externally be able to apply values for x (outside of the object, and later on)... I thought that perhaps I could just do:

var obj = {
            init: function() {
              // do something nice here...
          },

            func: function() {
              return x;
          }
    };

var foo = {
            doIt: function() {

              var init = obj.init;
              var x;

              obj.init = function() {
                x = 456;
                init.apply(obj);
              }

              obj.init();
              obj.func();
          }
};

foo.doIt();
==> (error) x is not defined

However, it doesn't work.. Is this possible to do somehow?

Thanks.

Upvotes: 0

Views: 64

Answers (1)

Anurag
Anurag

Reputation: 141929

You could create objects of your type using the new operator, and set the property on that object.

function Foo() {
    this.init = function() {
        this.x = -1;
    };

    this.func = function() {
        return this.x;
    };
}

var o = new Foo;
o.x = 941;
o.func(); // 941
o.x = 22;
o.func(); // 22

Upvotes: 1

Related Questions