如何允许JQuery事件处理程序访问模块模式中的变量

时间:2014-02-08 05:36:06

标签: javascript jquery

var MODULE = (function() {
    var app = {
        hi: "hi mom", // I can't access this. Oh' what do I do?
        onSubmitClick: function() {
            $('button').click(function() {
                console.log(hi); // I want to access the above hi variable..eeek!
            })
        },
        run: function() {
            this.onSubmitClick()
        }
    }
    return app
}());

var newApp = MODULE;
newApp.run();

2 个答案:

答案 0 :(得分:0)

hi不是变量,它是对象app

的属性
var MODULE = (function () {

    var app = {
        hi: "hi mom",
        onSubmitClick: function () {
            $('button').click(function () {
                console.log(app.hi); //use the app object and access the property
            })
        },
        run: function () {
            this.onSubmitClick()
        }
    }
    return app
}());


var newApp = MODULE;
newApp.run();

演示:Fiddle

答案 1 :(得分:0)

你也可以这样做。

var app = {
        hi: "hi mom",
        onSubmitClick: function (cthis) {
            $('button').click(function () {
                alert(cthis.hi); //use the app object and access the property
            })
        },
        run: function () {

            this.onSubmitClick(this);
            //-------------------^ this is referring app
        }
    }

Demo