Johan
Johan

Reputation: 35223

Accessing variables outside of closure

var MyClass = (function () {

    var _data;

    var cls = function () { };

    cls.prototype = {

        init: function(data){
            _data = data;
        }
    };

    cls.foo = _data;
    cls.bar = 1;

    return cls;
})();

var someData = { foo: true };

var cls = new MyClass();
cls.init(someData);

console.log(MyClass.foo); //undefined
console.log(MyClass.bar); //1

Why isn't MyClass.foo set here? It is being set in the init() method which I run above it. Hence it should return { foo: true }. What did I miss?

Upvotes: 1

Views: 90

Answers (2)

Aadit M Shah
Aadit M Shah

Reputation: 74244

I believe this is what you want:

function MyClass() { }

MyClass.prototype.init = function (data) {
    MyClass.foo = data;
};

MyClass.bar = 1;

Now it'll work as expected:

var someData = { foo: true };

var cls = new MyClass;
cls.init(someData);

console.log(MyClass.foo);
console.log(MyClass.bar);

See the demo here: http://jsfiddle.net/gTDZk/

Upvotes: 1

Amadan
Amadan

Reputation: 198566

cls.foo = _data; will not alias cls.foo to _data. It simply copies _data's value, which at the time the line is executed is undefined.

Either set cls.foo inside init, or (better) make cls.foo dynamic, as function() { return _data; }.

Upvotes: 2

Related Questions