2

我只是想知道为什么必须在下面的脚本中使用一个临时变量“ that ”(用当前分配的对象初始化,即“ this ”):

$(document).ready(function() {

    function ChatViewModel() {

        var that = this;

        that.userName = ko.observable('');
        that.chatContent = ko.observable('');
        that.message = ko.observable('');
        that.messageIndex = ko.observable(0);
        that.activePollingXhr = ko.observable(null);


        var keepPolling = false;

        that.joinChat = function() {
            if (that.userName().trim() != '') {
                keepPolling = true;
                pollForMessages();
            }
        }

        function pollForMessages() {
            if (!keepPolling) {
                return;
            }
            var form = $("#joinChatForm");


            that.activePollingXhr($.ajax({url: form.attr("action"), type: "GET", data: form.serialize(), cache: false,
                success: function(messages) {
                    console.log(messages);
                    for (var i = 0; i < messages.length; i++) {
                        that.chatContent(that.chatContent() + messages[i] + "\n");
                        that.messageIndex(that.messageIndex() + 1);
                    }
                },
                error: function(xhr) {
                    if (xhr.statusText != "abort" && xhr.status != 503) {
                        resetUI();
                        console.error("Unable to retrieve chat messages. Chat ended.");
                    }
                },
                complete: pollForMessages
            }));
            $('#message').focus();
        }

        that.postMessage = function() {
            if (that.message().trim() != '') {
                var form = $("#postMessageForm");
                $.ajax({url: form.attr("action"), type: "POST",
                    data: "message=[" + that.userName() + "] " + $("#postMessageForm input[name=message]").val(),
                    error: function(xhr) {
                        console.error("Error posting chat message: status=" + xhr.status + ", statusText=" + xhr.statusText);
                    }
                });
                that.message('');
            }
        }

        that.leaveChat = function() {
            that.activePollingXhr(null);
            resetUI();
            this.userName('');
        }

        function resetUI() {
            keepPolling = false;
            that.activePollingXhr(null);
            that.message('');
            that.messageIndex(0);
            that.chatContent('');
        }

    }

    //Activate knockout.js
    ko.applyBindings(new ChatViewModel());

});

为什么我不能只使用“ this ”?谁能解释一下?

4

2 回答 2

5

this总是指调用时范围内的对象,这可能会根据您的代码而改变。如果您希望它仍然是子函数中的对象,那么将其分配给不会改变值的变量可以解决此问题。

于 2013-03-11T12:57:49.357 回答
1

这是指所有者。你可以像这样重写你的代码:

$(document).ready(function() {

function ChatViewModel() {

    var that = this;

    this.userName = ko.observable('');
    this.chatContent = ko.observable('');
    this.message = ko.observable('');
    this.messageIndex = ko.observable(0);
    this.activePollingXhr = ko.observable(null);


    var keepPolling = false;

    this.joinChat = function() {
        if (that.userName().trim() != '') {
            keepPolling = true;
            pollForMessages();
        }
    }

    function pollForMessages() {
        if (!keepPolling) {
            return;
        }
        var form = $("#joinChatForm");


        this.activePollingXhr($.ajax({url: form.attr("action"), type: "GET", data: form.serialize(), cache: false,
            success: function(messages) {
                console.log(messages);
                for (var i = 0; i < messages.length; i++) {
                    that.chatContent(that.chatContent() + messages[i] + "\n");
                    that.messageIndex(that.messageIndex() + 1);
                }
            },
            error: function(xhr) {
                if (xhr.statusText != "abort" && xhr.status != 503) {
                    resetUI();
                    console.error("Unable to retrieve chat messages. Chat ended.");
                }
            },
            complete: pollForMessages
        }));
        $('#message').focus();
    }

    this.postMessage = function() {
        if (that.message().trim() != '') {
            var form = $("#postMessageForm");
            $.ajax({url: form.attr("action"), type: "POST",
                data: "message=[" + that.userName() + "] " + $("#postMessageForm input[name=message]").val(),
                error: function(xhr) {
                    console.error("Error posting chat message: status=" + xhr.status + ", statusText=" + xhr.statusText);
                }
            });
            that.message('');
        }
    }

    this.leaveChat = function() {
        that.activePollingXhr(null);
        resetUI();
        that.userName('');
    }

    function resetUI() {
        keepPolling = false;
        that.activePollingXhr(null);
        that.message('');
        that.messageIndex(0);
        that.chatContent('');
    }

}

//Activate knockout.js
ko.applyBindings(new ChatViewModel());
//fixing bracet
});

检查此链接:http ://www.quirksmode.org/js/this.html

于 2013-03-11T13:09:21.187 回答