Javascript self executing functions and variable scope

别来无恙 提交于 2019-12-13 05:12:32

问题


Could someone explain to me this behavior?

var obj = function()
{
    var _bar = 10;
    function i_bar(){return ++_bar;}

    return {
        bar  : _bar,
        i_bar: i_bar
    }
}();

obj.bar     // prints 10, OK
obj.i_bar() // prints 11, OK
obj.bar = 0 // prints 0,  OK
obj.i_bar() // prints 12, NOK

Since the only variable is _bar, shouldn't the last obj.i_bar() have printed 1 instead of 12?


回答1:


Your bar is not the same references as what i_bar is referencing. Value types are not by reference, so you are copying bar into the return object, but it is not the bar that your function is referring to. Try this:

var obj = function()
{
    var self = this;

    function i_bar(){return ++self.bar;}

    self.bar = 10;
    self.i_bar = i_bar;

    return self;
}();


来源:https://stackoverflow.com/questions/18662325/javascript-self-executing-functions-and-variable-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!