How can you pass parameters to a function when using .call()
in Javascript?
When I pass parameters they are always undefined in the callback function
EDIT (an example):
I will have an options object in my plugin:
var options = {
errorCallback : function( errors ) {}
}
I will call this from my plugin like this:
var errors = "Test error list";
configs.errorCallback.call(errors);
I will initialise my plugin like this
$('#plugin-element').myPlugin(
{
'errorCallback' : function errorrCallbackFunction( errors ) {
console.log(errors) //always undefined
}
}
The first argument of call is the 'this' of the function. If you want to pass the variable as argument start from the second one.
configs.errorCallback.call(undefined, errors);
Here is the documentation: Function.prototype.call()
configs.errorCallback.call(errors);
This isn't necessary. You only need to use call
if you want to set the context of the function call. That means the value of this
within the callback.
If you don't want to set this
, then you can just call the function as you normally would:
configs.errorCallback(errors);
If you do want to set this
, then you need to set it as the first parameter to call
. Subsequent parameters are passed on to the function.
For example:
var configs = {
errorCallback : function( errors ) {}
};
configs.errorCallback.call(configs, errors);
Within errorCallback
, you can access configs
using the keyword this
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With