javascript对象文字内的事件处理程序

Pro*_*ter 5 javascript jquery scope object this

我正在尝试创建一个对象并从中分配单击处理程序.我已经意识到我不能这样做,因为"this"与按钮相关联,而不是对象文字,打破了对函数的访问.

"未捕获的TypeError:对象#没有方法'clearSelection'"

请看下面的小提琴.

http://jsfiddle.net/ebKk8/

这是代码供参考.除了说明问题外,它不应该在这个阶段做任何有用的事情:)

function ThingConstructor(someData) {
    var button = $("#someButton");
    return {

        initialise: function () {
            button.click(function () {
                // I want "this.clearSelection();" to target the 
                // "clearSelection" function below.
                // Instead, it targets the button itself.
                // How can i refer to it?
                this.clearSelection();
            });
        },

        clearSelection: function () {
            this.populateList($("#stuff"), someData);
            $("#adiv").empty();
            console.log("clearSelection");
        },

        populateList: function (var1, var2) {
            //do something to a list
        }
    }
}

$(function () {
    var test = ThingConstructor("someData");
    test.initialise();
});
Run Code Online (Sandbox Code Playgroud)

Nea*_*eal 10

this在点击处理程序是一个DOMElement而不是你的对象.

试试这个:

initialise: function() {
    var _this = this; //reference to this object
    button.on('click', function () {
        _this.clearSelection();  // use _this
    }).appendTo("body");
},
Run Code Online (Sandbox Code Playgroud)