简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM