开发者

Is there a way to keep this referenced in a callback?

开发者 https://www.devze.com 2023-02-25 08:55 出处:网络
Hard to explain with words, but here is what I quite often have in my code: var self_reference; self_reference = this;

Hard to explain with words, but here is what I quite often have in my code:

var self_reference;
self_reference = this;

$(selector).bind('event', function() {
  self_reference.someFunction();
});

Is there a way to write that without the need of a temporary variable (self_r开发者_StackOverflow中文版eference here) ?


No, there isn't.

this is context sensitive and this will be a different object inside the callback function. Unless you copy it somewhere it will be lost.


$(selector).bind('event', (function() {
  this.someFunction();
}).bind(this));

Function.prototype.bind is an ES5 extension to function.

You could use _.bind as a cross browser alternative or use $.proxy.

$(selector).bind('event', (_.bind(function() {
  this.someFunction();
}, this));

$(selector).bind('event', ($.proxy(function() {
  this.someFunction();
}, this));


You could take a look at the jQuery proxy function.

e.g.

$.getJSON(url, $.proxy(function()
{
  // this has now got the desired context
}, this));
0

精彩评论

暂无评论...
验证码 换一张
取 消