Javascript函数对象,这个关键字指向错误的对象

在javascript函数对象中使用时,我遇到了关于javascript“this”关键字的问题。 我希望能够创建一个对象来处理Modal弹出窗口(JQuery UI对话框)。

该对象称为CreateItemModal。 我希望能够实例化并传递一些配置设置。 其中一个配置设置。 调用show方法时,将显示对话框,但取消按钮不起作用,因为它指的是DOM对象而不是CreateItemModal对象。

我该如何解决这个问题,或者是否有更好的方法将单独的行为放在单独的“类”或“对象”中。 我尝试了几种方法,包括将“this”对象传递给事件,但这并不像是一个干净的解决方案。

请参阅下面的(简化)代码:

function CreateItemModal(config) { // initialize some variables including $wrapper }; CreateItemModal.prototype.show = function() { this.$wrapper.dialog({ buttons: { // this crashes because this is not the current object here Cancel: this.close } }); }; CreateItemModal.prototype.close = function() { this.config.$wrapper.dialog('close'); }; 

你需要创建一个闭包来捕获this上下文,我倾向于使用匿名函数来执行此操作,如下所示: –

 CreateItemModal.prototype.show = function() { this.$wrapper.dialog({ buttons: { // this crashes because this is not the current object here Cancel: (function(self) { return function() { self.close.apply(self, arguments ); } })(this); } }); }; 

在JavaScript中遇到“this”问题的每个人都应该阅读并消化这篇博文: http : //howtonode.org/what-is-this

你也可以选择谷歌“道格拉斯克罗克福德”并观看他的一些(免费)video。

试试这个:

 CreateItemModal.prototype.show = function() { var me = this; this.$wrapper.dialog({ buttons: { // this crashes because this is not the current object here Cancel: me.close } }); }; 

它之所以不起作用,是因为“this”指的是对话框,而不是指那个类。

尝试添加一个等于全局的变量,例如

 function CreateItemModal(config) { // initialize some variables including $wrapper }; CreateItemModal.prototype.show = function() { var $this = this; this.$wrapper.dialog({ buttons: { // this crashes because this is not the current object here Cancel: $this.close } }); 

至于我,它在大多数情况下都有效