The real purpose of apply () and call () is to expand the scope in which the function is to run
Three-point description:
1 . Each function contains two non-inherited methods: Apply () and call ().
2 . They are used in the same way, and are called functions in a specific scope.
3, the receiving parameters are different, apply () receives two parameters, one is the function run scope (this), and the other is a parameter array.
The first parameter of the call () method is the same as the Apply () method, but the arguments passed to the function must be enumerated.
Usage examples:
First Instance:
functionprint (A, B, C, D) {alert (a+ B + C +d); } functionexample (A, B, C, d) {//using the call method to borrow print, parameter explicit break-through transferPrint.call ( This, A, B, C, D); //use the Apply method to borrow print, the parameter is passed as an array, //here directly with the JavaScript method within the arguments array itselfPrint.apply ( This, arguments); //or encapsulate an array ofPrint.apply ( This, [A, B, C, d]); } //The "backlight script" is shown belowExample ("Back", "light", "foot", "Ben");View Code
A second example:
function Animal (name) { this. Name = name; This function () { alert (this. Name); } } function Cat (name) { Animal.call (this, name); } var New Cat ("Black cat"); Cat.showname ();
functionAnimal (name) { This. Name =name; This. ShowName =function() {alert ( This. Name); } } functionCat (name) {Animal.call ( This, name); } Cat.prototype=NewAnimal (); varCat =NewCat ("Black cat"); Cat.showname (); Alert (CatinstanceofAnimal);
Application of call () and apply () in JavaScript