如何在JQuery回调函数中获取对象引用?

假设我们有一个名为aObject的javascript对象,而test()函数在JQuery中用作回调函数

var aObject = { aVariable : 'whatever value', test : function() { // Trying to access property. But doesn't work as expected since I am getting the DOM element, not the aObject reference var temp = this.aVariable; } } var anInstanceOfAObject = $.extend({}, aObject); anInstanceOfAObject.someFunction = function () { // I have to put "this" in a variable since "this" in the context below refers to the DOM element, not the instance of the object var placeHolder = this; $('some random div.element').theJavascriptFunction({ "theJavascriptCallbackFunction": placeHolder.test, }); } 

在test()函数内部,通常“this”的上下文是DOM元素。 我的问题是如何引用aObject,因为我们不能使用“this”来引用它。

编辑:我不确定上面的语法是否是实例化对象的正确/首选方式。 我看到一些使用这种语法的例子

 var aObject = function() {.... 

如果这似乎与问题有关,请通知我。

你只需要包装你的方法调用来获得正确的:

 anInstanceOfAObject.someFunction = function () { var placeHolder = this; $('some random div.element').theJavascriptFunction({ "theJavascriptCallbackFunction": function() { placeHolder.test() } }); } 

当你只使用placeHolder.test作为回调时,你只是将一个引用移交给test函数,并且将使用DOM元素调用该函数。

你也可以尝试bind

 anInstanceOfAObject.someFunction = function () { var placeHolder = this; $('some random div.element').theJavascriptFunction({ "theJavascriptCallbackFunction": this.test.bind(this) }); } 

如果你用$ .proxy(函数,这个)包装一个jquery函数调用,那么jquery将修复你对它的引用,以便它按照你想要的方式工作。

首先,你的问题是正确的。 但是,您的代码不起作用,并且当它修复时它说明了问题的解决方案。 简短的一课:如果您首先调试问题代码,您将了解更多信息!


下面我将提供问题,您说明的解决方案和更优雅的解决方案。


这是有问题的对象:

 var aObject = { aVariable : 'whatever value', test : function() { // Trying to access property. //But doesn't work as expected since I am getting //the DOM element, not the aObject reference var temp = this.aVariable; alert("temp=" + temp); } } 

以下是问题的示例:

 var anInstanceOfAObject = $.extend({}, aObject); anInstanceOfAObject.someFunction = function() { $(function() { //The problem. 'this' is not set after calling the fn via jquery. this.test(); }); anInstanceOfAObject.someFunction(); 

这是您编码的解决方案:

 var anInstanceOfAObject = $.extend({}, aObject); anInstanceOfAObject.someFunction = function() { // by saving this in placeHolder you solve the problem. Good! var placeHolder = this; $(function() { // Your solution works. Here you pass forward your ref to this placeHolder.test(); }); } anInstanceOfAObject.someFunction(); 

最后这里是一个稍微优雅的答案:

 var anInstanceOfAObject = $.extend({}, aObject); anInstanceOfAObject.someFunction = function() { $( $.proxy(function(){ // using $.proxy gets jquery to fix your this ref this.test(); },this) ); } anInstanceOfAObject.someFunction(); 

这总是指dom元素。 获取与你需要再次将它包装在jquery中的元素相关的jQuery对象,所以要么是$(this),要么是jQuery(this),具体取决于你的设置。