NibblyPig
NibblyPig

Reputation: 52932

Is it possible to preserve 'this' when calling a function in javascript via an anonymous function?

Let's say I have a jquery plugin that has an onSelect attribute. The user sets it to a function, and when that function is called, this refers to the object the plugin is applied to. All is good.

If I want to write a plugin that wraps this plugin, in order to inject some code into the onSelect, I do something like this:

// Get whatever the user put in
var extOnSelect = options['onSelect'];

// delete the onSelect attribute
delete options['onSelect'];

// re-add onSelect as an anonymous function that calls my method and the user's
var options = $.extend({ 
    'onSelect': function() { onSelect(); extOnSelect(); }
    }, options);

// call the plugin that I am wrapping / injecting extra onSelect code into
$(this).externalPlugin(options);

Then it will pass in my own onSelect code, while preserving what the user entered.

The only problem is, within each of those two functions this no longer refers to the object, it now refers to I think the generic inline function.

What's the best solution to fix this?

Upvotes: 2

Views: 998

Answers (2)

Bergi
Bergi

Reputation: 664444

Use apply and the arguments object:

extOnSelect.apply(this, arguments);

to call extOnSelect exactly like the current function.

You could use call, but then you would need to pass the event object (and other possibe arguments) explicitly.

Upvotes: 3

yakxxx
yakxxx

Reputation: 2941

I think you need to use call method of javascript functions.

var options = $.extend({ 
'onSelect': function() { onSelect.call(this); extOnSelect.call(this); }
}, options);

Upvotes: 1

Related Questions