我写了一些js:
var folersTreeMgr = {
sendDeleteFolderRequestAndUpdateFoldersTree: function () {
...
} else {
createAjaxRequest("Manager/DeleteLocation", {
'locationId': folder_minimal_descriptor.locationId
}).done(function (isSucceeded) {
if (isSucceeded) {
folersTreeMgr.deleteFolderInFoldersTree(); // works
this.deleteFolderInFoldersTree(); // doesn't work
deleteFolderInFoldersTree(); // doesn't work
}
//TODO: else: error
});
}
},
deleteFolderInFoldersTree: function () {
$("#jstree").jstree("remove", null);
}
};
为什么我会收到“缺少功能”错误
答案 0 :(得分:6)
因为您在回调中使用this
,因为它具有不同的含义。
您可以在变量中引用外部this
,然后在回调中使用它。
var folersTreeMgr = {
sendDeleteFolderRequestAndUpdateFoldersTree: function () {
var self = this; // cache it
...
} else {
createAjaxRequest("Manager/DeleteLocation", {
'locationId': folder_minimal_descriptor.locationId
}).done(function (isSucceeded) {
if (isSucceeded) {
self.deleteFolderInFoldersTree(); // works
}
});
}
},
deleteFolderInFoldersTree: function () {
$("#jstree").jstree("remove", null);
}
};
或使用$.proxy
保留this
值...
createAjaxRequest("Manager/DeleteLocation", {
'locationId': folder_minimal_descriptor.locationId
}).done( $.proxy(function (isSucceeded) {
if (isSucceeded) {
this.deleteFolderInFoldersTree(); // works
}
},this) );
这将返回一个函数,该函数将$.proxy
的第二个参数绑定到作为第一个参数传递的函数。
答案 1 :(得分:2)
当您致电this.deleteFolderInFoldersTree()
时,您处于不同的环境中,这意味着this
不再是对象。解决这个问题的快速方法如下:
var self = this;
然后执行self.deleteFolderInFoldersTree()