Comparison of the call and apply functions in Javascript and the use of the example _ javascript technique

Source: Internet
Author: User
This article mainly introduces the comparison and examples of the call and apply functions in Javascript. This article attempts to use a clearer and simpler way of thinking to analyze and explain the two functions, for more information about some simple Javascript operations, call and apply functions are rarely used. in other large operations, such as web application development, js framework development may often encounter these two functions. There are also a lot of information on the Internet about the two functions, but I think that a lot of information is either based on the book or highly similar, lack of ground interpretation. Next, I try to explain these two functions with a clearer and simpler idea.

The code is as follows:


We can regard call () and apply () as the methods of an object and call the function indirectly through the implementation of the call method. The first real parameter of call () and apply () is the parent object of the function to be called. it is the call context and can be referenced by this in the function body. To call the function f () through the method of object o, call () and apply (): f. call (o) f. apply (o). [1] can be used in this way.

First, let's analyze the call. here we have the ECMAScript 3rd Edition's explanation of the call function [2]: when the call method is called by a function object (func. call (0), you need to input a required parameter and several non-required parameters, its execution process is as follows:
A. If the call object cannot be run, a TypeError is thrown.
B. the parameter list is empty.
C. if more than one parameter is input to the called method, arg1, arg2... Insert to parameter list
D. return the call function result. replace this in the call function (func) with input parameter 1 and use the input parameter list as the function parameter.
In fact, the call function is the prototype of the function object. that is to say, when the call function must be a function, replace this in the call function with the input object. The following is an example:

Script function C1 () {this. name = 'Zhang San'; this. age = '24'; this. sayname = function () {console. log ("Here is the C1 class, my name is:" + this. name + "My age is" + this. age) ;}} function C2 () {this. name = 'Lily'; this. age = '25';} var c1 = new C1 (); var c2 = new C2 (); c1.sayname (); c1.sayname. call (c2); script

Execution result:
Here is the C1 class. my name is Zhang San. my age is 24.
Here is the C1 class. my name is Li Si. my age is 25.
In the code above, two classes are declared. C1, C2, and C1 have two attributes. one method, C2 also has two attributes identical to C1. After instantiation, c1.sayname () the actual property is printed, c1.sayname. call (c2) prints the properties except c2. why? Because sayname () is a function and the function contains this, after the call is executed, this will be replaced by c2. Therefore, the c2 attribute will be printed.
The difference between apply and call lies in the passing of optional parameters. all optional parameters of apply are stored in an array. when a parameter is input, call is divided into multiple parameters.
So what are the applications of the apply and call functions? The first is to find the largest element in the number array in the classic network, and use Math directly. max. apply (null, array). The other one can be inherited using apply and call, as shown below:

Script function Human (name, sex) {this. name = name; this. sex = sex; this. walk = function () {console. log ('I am walking');} function Child () {Human. call (this, "James", "male") this. paly = function () {console. log ('I like play');} this. intruduce = function () {console. log ('Hello everyone, I am '+ this. name) ;}} var jindium = new Human ('Jack', 'mal'); var xiaoping = new Child (); xiaoping. walk (); xiaoping. paly (); xiaoping. intruduce (); script

Execution result:
I'm walking
I like playing very much.
Hello everyone, I'm James.
A function similar to call () and apply () is bind (), which is a new method added in ECMAScript 5, but bind () can be easily simulated in ECMAScript 3 (). The bind Function is also the Function. prototype method in Javascript. The main content of this method is to bind the Function to an object. When the bind () method is bound to function f () and an object o is input as a parameter, this method returns a new function and calls it as an o method. Any arguments passed in the new function are passed in to the original function. As follows:

Script function introduce (country, holobby) {return "Hello, My name is" + this. name + ", this year" + this. age + "years old, from" + country + ", like" + holobby;} var xiaoming = {name: "James", age: 20} var jieshao = introduce. bind (xiaoming); console. log (jieshao ("China", "playing"); script

Execution result:
Hello everyone, my name is James. I am 20 years old and come from China. I like playing basketball.
The above example is equivalent:

Script function introduce (country, holobby) {return "Hello, My name is" + this. name + ", this year" + this. age + "years old, from" + country + ", like" + holobby;} var xiaoming = {name: "James", age: 20} console. log (introduce. apply (xiaoming, ["China", "play"]); // or the following console. log (introduce. call (xiaoming, "China", "playing"); script

Note that in the strict mode of ECMAScript 5, the first real parameter of call () and apply () will change to the value of this, even if the input real parameter is the original value or even null or undefined. In ECMAScript 3 and non-strict mode, the input null and undefined values are replaced by global variables, and other original values are replaced by corresponding packaging objects.

References

[1], Javascript authoritative guide version 6th, page 189
[2], Function. prototype. call (thisArg [, arg1 [, arg2 ,... ])
[3], Function. prototype. apply (thisArg, argArray)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.