开发者

Javascript Objects and jQuery

I'm not sure what the best way to approach this is.

I have a control that I want to be able to open and persist some data or change it on the fly.

function TaskControl(params) {
    this.params = params;

    this.openTaskControl = function () {
        alert("openTaskControl");
    }

    $("#button").click(function () {
        th开发者_JS百科is.openTaskControl();
    });
}

The problem I'm having is that trying to call openTaskControl throws an error because this apparently refers to the HTML element and not the TaskControl. How do I call this function from inside the click function?


function TaskControl(params) {
        this.params = params;
        var that = this;

        this.openTaskControl = function () {
                alert("openTaskControl");
        }

        $("#button").click(function () {
                that.openTaskControl();
        });
}


The inner scope will refer to a different this object. Use variables instead:

function TaskControl(params) {
    var paramsSave = params;

    var openTaskControl = function () {
        alert("openTaskControl");
    }

    $("#button").click(function () {
        openTaskControl();
    });
}


Here is a good discussion on how to use the this keyword in javascript: http://www.quirksmode.org/js/this.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜