I’m interested what’s the reason to have call() method in JS. It seems it duplicates usual method of calling this.
For example, I have a code with call().
var obj = {
objType: "Dog"
}
f = function(did_what, what) {
alert(this.objType + " " + did_what + " " + what);
}
f.call(obj, "ate", "food");
The output is “Dog ate food”. But the same result I can get assigning the function to the object.
var obj = {
objType: "Dog"
}
f = function(did_what, what) {
alert(this.objType + " " + did_what + " " + what);
}
obj.a = f;
obj.a("ate", "food");
The result is the same. But this way is more understandable and convenient to use. Why call() is needed?
callis used when you want to control the scope that will be used in the function called. You might want thethiskeyword to be something else than the scope you assigned the function to, in those cases you can usecallorapplyto call the function with your own scope.F.ex, it also allows you to call utility methods outside the scope, like when using “private” functions:
In the example above,
privateFnis not exposed inobjbut it can still be constructed as if it was a part of the public scope (usingthisin the same way).