简体   繁体   English

访问闭包之外的变量

[英]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? 为什么MyClass.foo不在这里设置? It is being set in the init() method which I run above it. 它是在我运行的init()方法中设置的。 Hence it should return { foo: true } . 因此它应该返回{ foo: true } What did I miss? 我错过了什么?

cls.foo = _data; will not alias cls.foo to _data . 不会别名cls.foo_data It simply copies _data 's value, which at the time the line is executed is undefined . 它只是复制_data的值,在执行该行时,该值是undefined

Either set cls.foo inside init , or (better) make cls.foo dynamic, as function() { return _data; } init设置cls.foo ,或者(更好)使cls.foo动态化,如function() { return _data; } 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/ 请参阅此处的演示: http//jsfiddle.net/gTDZk/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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