Comparison of call and apply functions in JavaScript and _javascript techniques for using instances

Source: Internet
Author: User

Few simple JavaScript operations will use the call and apply functions, and in other larger operations such as Web application development, JS Framework development may often encounter these two functions. On the interpretation of these two functions, there are a lot of information on the Internet, but I think a lot of information is either scripted or highly similar, lack of grounding gas interpretation. I then tried to explain the two functions in a clearer and simpler way.

Copy Code code as follows:

We can call the call () and apply () as a method of an object, calling the function indirectly by invoking the method's implementation. The first argument of call () and apply () is the parent object that is to invoke the function, which is the invocation context, which is used in the function body to obtain a reference to it. To invoke the function f () on the method of object o, you can use call () and apply (): F.call (o) f.apply (o). [1]

First, let's analyze call, which has the ECMAScript 3rd edition interpretation of the called function [2]: When the calling method is invoked by a function object (Func.call (0)), a necessary argument and several unnecessary arguments are passed in. The process of its execution is this:
A, if the object calling call is not running, throw a typeerror error.
b, set the parameter list to empty
C, if the called method passed in more than one parameter, then the ARG1,ARG2 ... Insert INTO parameter list
D, return the function result called call, replace the this in the Call function (func) with the passed parameter 1, and take the incoming argument list as an argument to the function.
In fact, the call function is the prototype of a function object, that is, when a function called calls must also be a function, and when called, the call is replaced with the object in the function called. Here's an example:

<script>
 function C1 () {
 this.name= ' john ';
 This.age= ';
 This.sayname=function () {
  Console.log ("Here is the C1 class, my name is:" +this.name+ "my Age is" +this.age);
 }
 function C2 () {
 this.name= ' dick ';
 This.age= ';
 }
 var c1=new C1 ();
 var c2=new C2 ();
 C1.sayname ();
 C1.sayname.call (C2);
</script>

Execution results:
Here is the C1 class, my name is: John my age is 24
Here is the C1 class, my name is: Dick my age is 25
In the code above, two classes are declared, C1 and C2,c1 have two properties, one method, C2 two and C1, and after instantiation, C1.sayname () prints out the actual properties, C1.sayname.call (C2) prints the properties except for the C2. Why is that so? Because Sayname () is a function, and the function has this in the body, when call executes, this is replaced by C2, so the C2 property is eventually printed.
The difference between apply and call is the transfer of optional parameters, the optional parameters of apply are all stored in an array, as a parameter of the channeling and call is divided into multiple parameters.
So what are the application and call functions? The first is the network on the comparison of the classical number of the largest array of elements, directly with Math.max.apply (Null,array) can be, the other is to apply and call to achieve inheritance, as follows:

<script> 
 function Human (name,sex) {
 this.name=name;
 This.sex=sex;
 This.walk=function () {
  Console.log (' I'm walking ');
 }
 function Child () {
 Human.call (this, "xiaoming", "male")
 this.paly=function () {
  console.log (' I enjoy playing ');
 }
 This.intruduce=function () {
  console.log (' Everyone good, I'm ' +this.name ')
 ;
 }
 var jinp=new Human (' Jack ', ' man ');
 var xiaoping=new child ();
 Xiaoping.walk ();
 Xiaoping.paly ();
 Xiaoping.intruduce ();
</script>

Execution results:
I was walking.
I like to play very much.
Hi, I'm xiaoming.
A function similar to call () and apply () is bind (), which is a new method in ECMAScript 5, but can easily simulate bind () in ECMAScript 3. The BIND function is also a Function.prototype method in JavaScript, and the main content of this method is to bind a function to an object. When the function f () is bound with the bind () method and passes in an object o as an argument, this method will return a new function as an O method to invoke. Any arguments passed in the new function are passed in to the original function. As follows:

<script>
 function Introduce (country,hobby) {return
 "Hello everyone, my name is" +this.name+ ", this year" +this.age+ "years, from" + Country+ ", like" +hobby;
 }
 var xiaoming={name: "Xiaoming", age:20}
 var jieshao=introduce.bind (xiaoming);
 Console.log (Jieshao ("China", "play"));
</script>

Execution results:
Hello, my name is Xiao Ming, 20 years old this year, from China, like playing ball
The above example is equivalent to:

<script>
 function Introduce (country,hobby) {return
 "Hello everyone, my name is" +this.name+ ", this year" +this.age+ "years, from" + Country+ ", like" +hobby;
 }
 var xiaoming={name: "Xiaoming", age:20}
 Console.log (introduce.apply (xiaoming,["China", "play"));
    or the following
 Console.log (Introduce.call (xiaoming, "China", "play");
</script>

Note that in the strict mode of ECMAScript 5, the first argument of call () and apply () becomes the value of this, even if the incoming argument is the original value or even null or undefined. In ECMAScript 3 and non rigorous mode, the incoming null and undefined are replaced by the global play one, while the other original values are replaced by the corresponding wrapper objects.

Resources

[1], JavaScript authoritative guide 6th edition, 189 pages
[2], Function.prototype.call (Thisarg [, Arg1 [, arg2, ...]])
[3], Function.prototype.apply (Thisarg, Argarray)

Related Article

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.