2010-03-22 66 views
4

我有一个问题,关于在javascript函数对象中使用javascript“this”关键字。我希望能够创建一个对象来处理模式弹出(JQuery UI对话框)。Javascript函数对象,这个关键字指向错误的对象

该对象称为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'); 
}; 

回答

4

你需要创建一个封闭套住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); 
     } 
    }); 
}; 
+0

这个工作,但是这是“最佳实践”?看起来像是一个很大的开销,让JavaScript看到这是一个真正的“OO”对象? – 2010-03-22 09:15:56

+0

那么,那是因为你使用的是jQuery,而jQuery并不能帮助你编写那种javascript。对于大多数其他框架,您只需编写'Cancel:this.close.bind(this)' – Alsciende 2010-03-22 09:20:41

+0

@Rody:这是唯一的做法。 ECMAScript第5版引入了函数原型方法'bind',它可以让你做这样的事情:'取消:this.close.bind(this);'。如果你必须在你的代码中多次执行这样的事情,那么在Web上有'bind'原型的实现。 – 2010-03-22 09:22:15

2

试试这个:

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

为什么它不工作的原因,因为 “这” 指的是对话,而不是那个班。

+0

很多upvotes上不正确的答案辉煌; P。上面的代码没有改变。 close函数仍然在button元素的上下文中执行而不是'CreateItemModal'实例。 – AnthonyWJones 2010-03-22 09:12:17

+0

正确,只是在一分钟前测试过,而且这不会不幸地工作。 – 2010-03-22 09:16:46

+0

没错,因为'me.close'作为一个函数存储在'Cancel'中:它的包含对象'me'丢失了。所以'this'在执行时是'window'。 – Alsciende 2010-03-22 09:19:33

0

尝试添加一个变量等于全球这个如

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 
    } 
}); 

对我来说,它的工作原理在大多数情况下

3

大家谁遇到问题,“这个”在JavaScript应该阅读和消化这篇博客文章:http://howtonode.org/what-is-this

你也会对谷歌“道格拉斯克罗克福德”做的很好,并观看他的一些关于这个主题的(免费)视频。

相关问题