开发者

JavaScript scope confusion

开发者 https://www.devze.com 2023-01-28 15:51 出处:网络
I have this definition of TabList: MyApp.TabList = function (selector) { var private = { $list: $(selector),

I have this definition of TabList:

MyApp.TabList = function (selector) {

    var private = {
        $list: $(selector),
        tabs: []
    };

    this.add = function (tab) {
        private.tabs.push(tab);
    };
};

When I call this, however, and break in the body of this.add, private doesn't appear in the local scope:

MyApp.tabs = new MyApp.TabList("#tabs");

$("#tab-add").click(function() {
    MyApp.tabs.add(new MyApp.Tab("title"));
});

Does private not retain inside the object?

If this code works standalone as above, I might have missed something—I tried to 开发者_开发知识库simply it the best I could for demonstrative purposes.


Because of the closure property, the variable should definitely be available within the add() function.

This might not be the answer, but private is a Javascript keyword. You should try avoiding using it as a name for a variable. It can cause unknown bugs to arise, and sometimes debuggers won't help. Give it a shot and let us know if it works!

0

精彩评论

暂无评论...
验证码 换一张
取 消