Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果我使用prototype创建OOPJS代码,我如何从循环中引用类方法?_Javascript_Jquery_Oop - Fatal编程技术网

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(或其他示例),可以正确保存引用。非常感谢!