Javascripts . call() and . apply() methods allow you to set the context for a function. var myfunc = function(){ alert(this.name); }; var obj_a = { name: "FOO" }; var obj_b = { name: "BAR!!" };
Context in JavaScript is related to objects. It refers to the object within the function being executed. this refers to the object that the function is executing in.
var object = {}; function fn(){ return this; } assert( fn() == this, "The context is the global object." ); assert( fn. call(object) == object, "The context is changed to a specific object."
Javascripts .call()
and .apply()
methods allow you to set the context for a function.
var myfunc = function(){
alert(this.name);
};
var obj_a = {
name: "FOO"
};
var obj_b = {
name: "BAR!!"
};
Now you can call:
myfunc.call(obj_a);
Which would alert FOO
. The other way around, passing obj_b
would alert BAR!!
. The difference between .call()
and .apply()
is that .call()
takes a comma separated list if you're passing arguments to your function and .apply()
needs an array.
myfunc.call(obj_a, 1, 2, 3);
myfunc.apply(obj_a, [1, 2, 3]);
Therefore, you can easily write a function hook
by using the apply()
method. For instance, we want to add a feature to jQuerys .css()
method. We can store the original function reference, overwrite the function with custom code and call the stored function.
var _css = $.fn.css;
$.fn.css = function(){
alert('hooked!');
_css.apply(this, arguments);
};
Since the magic arguments
object is an array like object, we can just pass it to apply()
. That way we guarantee, that all parameters are passed through to the original function.
Use function.call
:
var f = function () { console.log(this); }
f.call(that, arg1, arg2, etc);
Where that
is the object which you want this
in the function to be.
Another basic example:
NOT working:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
};
img.src = reader.result;
Working:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
}.bind(this);
img.src = reader.result;
So basically: just add .bind(this) to your function
You can use the bind function to set the context of this
within a function.
function myFunc() {
console.log(this.str)
}
const myContext = {str: "my context"}
const boundFunc = myFunc.bind(myContext);
boundFunc(); // "my context"
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