Javascript 如果我使用prototype创建OOPJS代码,我如何从循环中引用类方法?
我将首先向您展示我的代码:Javascript 如果我使用prototype创建OOPJS代码,我如何从循环中引用类方法?,javascript,jquery,oop,Javascript,Jquery,Oop,我将首先向您展示我的代码: function Messages(){ this.postResponseButton = '#postResponseButton'; $(document).ready(this.setEvents); } Messages.prototype.setEvents = function(){ $(self.postResponseButton).click(function(){ this.postResponse();
function Messages(){
this.postResponseButton = '#postResponseButton';
$(document).ready(this.setEvents);
}
Messages.prototype.setEvents = function(){
$(self.postResponseButton).click(function(){
this.postResponse(); // ERROR HERE
});
}
Messages.prototype.postResponse = function(){
console.log('Post Response');
}
var messages = new Messages();
在标记行(“此处出错”)中,当我将其称为this.postress()
时,它无法识别Messages.postress()
函数。我还尝试了self.postress()
,但没有成功
我确信这是一个范围问题;我只是不知道如何引用实际对象。我需要设置var me=this
并使用它吗
谢谢你的时间 正如您所说,问题在于
单击事件处理程序的上下文与它出现的函数不同。或者(ES5在旧浏览器中不起作用)将函数设置为this
:
Messages.prototype.setEvents = function(){
$(self.postResponseButton).click(function(){
this.postResponse();
}.bind(this));
}
或者保存对该
的引用,并改用该引用:
Messages.prototype.setEvents = function(){
var that = this;
$(self.postResponseButton).click(function(){
that.postResponse();
});
}
第三种选择是使用,它实际上是Function.prototype.bind
的别名,包括旧浏览器的回退:
Messages.prototype.setEvents = function(){
$(self.postResponseButton).click($.proxy(function(){
this.postResponse();
}, this));
}
为什么您的构造函数设置了
这个.postResponseButton
,然后您阅读了self.postResponseButton
?我现在意识到我使用的是self
,因为这个
不起作用。我意识到此
不起作用,因为此
是通过$(document).ready()
函数传递的html文档。感谢您的全面回复!我尝试了每个示例,但一直收到以下错误:uncaughttypeerror:Object#没有方法“postress”
。似乎此
返回的是文档而不是实例。你知道为什么会这样吗?再次感谢。啊!我现在明白了。我在$(document).ready()函数中重复了相同的错误。因此,通过在document.ready()
和postResponse()
行中使用bind(或其他示例),可以正确保存引用。非常感谢!