You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jQuery回调函数内获取当前对象引用?

Fixing this Context in jQuery Callbacks for Object Methods

The issue you're facing is a common pitfall with JavaScript function context: when you pass aObject.test (or api_cache.handle_add_form_submit) directly as a callback to jQuery's submit() method, jQuery automatically sets this inside the callback to the DOM element that triggered the event (the form, in this case). This breaks your ability to access your object's properties like aVariable because this no longer refers to your object instance.

Your initial attempt using bind(this) didn't work because inside the $(document).ready() callback, this refers to the document object—not your api_cache instance. Here are three reliable ways to fix this:

1. Use Function.prototype.bind() (Modern Browsers)

Explicitly bind your method to your object instance. This creates a new function where this is permanently set to your object, regardless of how the function is called:

$(document).ready(function() { 
  $('#add_api_form').submit(api_cache.handle_add_form_submit.bind(api_cache)); 
});

2. Wrap the Method Call in a Function

You can use an arrow function (or a regular function for older browser support) to wrap the method call. When you invoke the method directly on your object, this inside the method will naturally refer to the object itself:

// Arrow function (modern browsers)
$(document).ready(function() { 
  $('#add_api_form').submit((e) => {
    api_cache.handle_add_form_submit(e);
  }); 
});

// Regular function (works in all browsers)
$(document).ready(function() { 
  $('#add_api_form').submit(function(e) {
    api_cache.handle_add_form_submit(e);
  }); 
});

3. Use jQuery's $.proxy() (Cross-Browser Compatibility)

jQuery provides its own $.proxy() method which serves the same purpose as bind(), and works in older browsers that don't support ES5's native bind():

$(document).ready(function() { 
  $('#add_api_form').submit($.proxy(api_cache.handle_add_form_submit, api_cache)); 
});

All three approaches will ensure that inside your handle_add_form_submit method, this refers to your api_cache object, letting you access properties like aVariable as expected.

内容的提问来源于stack exchange,提问作者Mohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:42:30