我开始学习 JavaScript 中的 OOP,并遇到了这个问题。 我有一个简单的对象:
function Notifications() {
this.button = $('#dLabel');
this.wrapper = $('#notifications');
this.elements = [];
}
Notifications.prototype = {
constructor: Notifications,
fetch: function() {
$.ajax({
method: "GET",
url: '/notifications.json'
}).done(function(data) {
this.elements = data;
this.refresh();
});
},
refresh: function() {
console.log("REFRESH");
}
}
$(function() {
var ns = new Notifications();
ns.fetch();
})
当我运行这个时,我得到:
Uncaught TypeError: this.refresh is not a function
是不是因为.done
函数中的this
不是Notifications
实例?我该如何解决这个问题?
最佳答案
使用bind()
method修复上下文:
Notifications.prototype = {
constructor: Notifications,
fetch: function() {
$.ajax({
method: "GET",
url: '/notifications.json'
}).done(function(data) {
this.elements = data;
this.refresh();
}.bind(this)); // <------- Use bind(this)
},
refresh: function() {
console.log("REFRESH");
}
}
done()
处理程序 function(data) {...}
作为一个简单的函数调用执行,它具有上下文 this
作为全局对象(窗口)或“严格模式”
中的未定义
。
Function.prototype.bind(newContent)
将上下文修改为 newContext
。
This section更详细地描述了 this
如何丢失以及如何防止丢失。
关于javascript - 在原型(prototype)中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36083905/