In JavaScript, each function has a call () and an apply () method, with the following examples:
First define an Some_obj object that has a say () Method:
var some_obj={
Name: ' Ninja ',
Say:function (WHO) {
Return ' Haya ' + who + ', I am a ' + this.name;
}
};
Call Some_obj.say (' Dude ');
Output: "Haya Dude, I am a Ninja"
Create an object again
var my_obj={name: ' Scripting guru '};
We now want to call the Say () method in Some_obj as a method of My_obj itself, in which case you can try the object method in the Say () function called ()
Some_obj.say.call (my_obj, ' Dude ');
Output: "Haya Dude, I am a Scripting guru";
In addition, if we do not pass the object to the first argument of call (), or to it is null, the calling object is defaulted to the global object (see note:);
Note: This refers to the global object, which in effect modifies the object function's this value through the first parameter of call;
If you use the object method apply ();
Some_obj.say.apply (my_obj,[' Dude ');
Output: "Haya Dude, I am a Scripting guru";
Thus, apply () and call () are basically the same, the difference is the transfer of the form of parameters, apply () The Parameter form is an array;
Pass more parameters: Some_obj.someMethod.call (my_obj, ' A ', ' B ', ' C ');
Summary of the call () and apply () Methods for function objects in JavaScript