简体   繁体   中英

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?

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; } function() { return _data; } .

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM