In JavaScript, call and apply are the two methods that the function object comes with, and the main function of these two methods is to change the this point in the functions, so as to achieve the effect of ' pick and move wood '. In this article, we will explain the two methods in detail, and put together a few classic scenarios for call and apply.
Pager (Thisargs [, args ...])
The method can pass a Thisargs parameter and a list of arguments, Thisargs specifies the caller of the function at run time, which is the this object in the function, and the argument list is passed into the calling function. The Thisargs values are in the following 4 cases:
(1) Do not pass, or pass null,undefined, function of this point to the Window object
(2) A function name that passes another function, the this in the function points to the reference to the function
(3) to pass an underlying type, such as a string, numeric, or Boolean type, which in the function points to its corresponding wrapper object, such as String, number, Boolean
(4) Passing an object, which in the function points to this object
functionA () {Console.log ( This); //Output The This object in function a }functionB () {} //define function B
varobj = {name: ' Onepixel '}; //define Object objA.call (); //windowA.call (NULL);//windowA.call (undefined);//windowA.call (1);// NumberA.call (");//StringA.call (true);//BooleanA.call (b);//function B () {}A.call (obj);//Object
This is the core function of call, which allows you to invoke a method on an object that is not defined by the object, and this method can access the properties in that object, as to what is the benefit of doing so, let's take a look at a simple example first:
var a = {name: ' Onepixel ', // Define the properties of a say: function () {// method for defining a Console.log ("Hi,i ' m function a!" ); }}; function b (name) {Console.log ( "Post params:" + name); Console.log ( "I ' m" + this .name); this .say ();} B.call (A, ' test ' >>post params:testi ' m Onepixeli ' m function a!
When B.call is executed, the string ' test ' is passed as a parameter to function B, and because of the function of call, the this in function B points to object A, so it is equivalent to invoking function B on object A, whereas in fact there is no B defined in a.
Apply (thisargs[,args[]])
The only difference between apply and call is that the second parameter is passed differently, the second argument of apply must be an array, and call allows a list of arguments to be passed. It is worth noting that although apply receives a parameter array, but when passed to the calling function, it is passed as a parameter list, let's look at a simple example:
function b (x, Y, z) { console.log (x, y, z);} B.apply (null// 1 2 3
This feature of apply is important and we will refer to this feature in the following scenario.
Application Scenario One: Inheritance
As you know, JavaScript does not have the Extend keyword in high-level languages such as Java, C #, so there is no concept of inheritance in JS, and if you must inherit it, call and apply can implement this function:
functionAnimal (name,weight) { This. Name =name; This. Weight =weight;}functionCat () {Animal.call ( This, ' cat ', ' 50 '); //animal.apply (this,[' cat ', ' []]); This. Say =function() {Console.log ("I am" + This. name+ ", my weight is" + This. Weight); }}varCat =NewCat (); Cat.say ();//I am cat,my weight is
When Cat is produced by the new operator, this in cat points to the Cat object (for a walkthrough of the new Operator, see: http://www.cnblogs.com/onepixel/p/5043523.html), The key to inheritance is that the Animal.call (this, ' cat ', ' 50 ') is executed in cat, passing this as the Thisargs parameter in call, so this in the animal method points to this in cat. And this in cat is pointing to a cat object, so this is the cat object in animal, and the name and weight properties are defined in animal, so the Cat object has the properties defined in the animal , thus achieving the purpose of inheritance.
Application Scenario Two: counter switch
Before we go into the following, let's begin by understanding one of the nonstandard jargon in javascript: Arraylike (class array/pseudo-array)
The Arraylike object, which has part of the behavior of the array, has long been shown in the DOM, and the rise of jquery has made Arraylike shine in JavaScript. The subtlety of the Arraylike object is that it is similar to the JS native array, but it is free to build, it comes from the developer's extension of the JavaScript object, that is to say: for its prototype (prototype) We are free to define, Without contaminating the JS native array.
Arraylike objects are widely used in JS, such as nodelist in the DOM, arguments in functions are class array objects, which store each element as an array, but it has no way of manipulating the array, and we can ' move some of the array's methods ' by call ' To the Arraylike object, thus achieving the purpose of manipulating its elements. For example, we can traverse the arguments in a function like this:
functionTest () {//to detect if arguments is an instance of arrayConsole.log (ArgumentsinstanceofArray,//falseArray.isarray (arguments)//false ); //determine if arguments has a foreach methodConsole.log (Arguments.foreach);//undefined //apply a foreach in an array to a argumentsArray.prototype.forEach.call (arguments,function(item) {Console.log (item);//1 2 3 4 });} Test (1,2,3,4);
In addition, for apply, we mentioned a unique feature of it, that is, apply receives an array, which is passed as a parameter list when passed to the calling function. This feature makes apply appear to be more notch above than call, such as a scene: given an array [1,3,4,7], and then the largest element in the array, and you know that there is no way to get the maximum value in the array, and generally you need to write code to implement it. And we know that there is a method in the Math object that gets the maximum value, that is, Math.max (), the Max method needs to pass a list of arguments, and then returns the maximum value in those parameters. Instead, apply can not only apply the Math object's Max method to other objects, but also convert an array to a parameter list and pass it to Max, so that the code can be seen at a glance:
var arr = [2,3,1,5,4]; Math.max.apply (null// 5
These are some of the more classic call and apply scenarios, mastering these skills and applying these features to your actual project will make your code look more intriguing!
by @ One pixel Blog Park 2016.01
Welcome to reprint and share, but please specify the source and connection!
Counter Switch--talking about call and apply in JavaScript