JavaScript 'this' 引用了错误的范围

javascript 'this' references wrong scope

本文关键字:范围 错误 this JavaScript 引用      更新时间:2023-09-26

我正在尝试在javascript中创建一个ViewModel,视图模型的部分功能是从Web加载数据并将其显示在UI端。我遇到了一个问题,因为我无法在某个回调函数中引用视图模型对象。情况如下:

LoggedInViewModel.prototype = {
getFriendList: function() {
    var self = this; // 'this' references the correct viewmodel object
    $.ajax({
        url: "api/users/friendlist",
        success: self.loadFriendListIntoModel
    });
},
loadFriendListIntoModel: function (friends) {
    var self = this;
    //'this' references the ajax object that called the function.
    // is there a way to make 'this' reference the actual viewmodel 
    // object here? i can do var self = model; but that feels hacky
    friends.forEach(function (friend) {
        //Uncaught TypeError: Cannot call method 'push' of undefined 
        self.friendList.push(new Friend(friend));
    });
}
};
var model = new LoggedInViewModel();
ko.applyBindings(model);
model.getFriendList();

你可以这样修复它:

getFriendList: function() {
    $.ajax({
        url: "api/users/friendlist",
        success: this.loadFriendListIntoModel,
        context: this
    });
},

或者像这样:

getFriendList: function() {
    var self = this; // 'this' references the correct viewmodel object
    $.ajax({
        url: "api/users/friendlist",
        success: function() {
            self.loadFriendListIntoModel();
        }
    });
},

或者像这样:

getFriendList: function() {
    $.ajax({
        url: "api/users/friendlist",
        success: $.proxy(this.loadFriendListIntoModel, this)
    });
},

阅读 $.ajax 了解上下文选项和关于 $.proxy。你也可以使用Function.prototype.bind方法。