Detailed explanation of four call methods for JavaScript Functions

Source: Internet
Author: User
Tags array example

In JavaScript, a function is a first-class citizen. A function is a data type in JavaScript, rather than being used as a module just like C # or other descriptive languages. There are four call modes for a function: function call form, method call form, constructor form, and apply form. The main difference among all the call modes here is the significance of the keyword "this". The following describes several call forms respectively.

Main content of this article:

1. Analyze the four call forms of functions
2. Find out the meaning of this in the function
3. clarify the process of constructing a letter object
4. Learn to call functions using context

I. function call form

Function call is the most common and understandable form. The so-called function form is generally called directly after the function is declared. For example:
Copy codeThe Code is as follows:
// Declare a function and call
Function func (){
Alert ("Hello World ");
}
Func ();
Or:
Copy codeThe Code is as follows:
// Define the function using the Lambda expression of the function, and then call
Var func = function (){
Alert ("Hello, programmer ");
};
Func ();
Both codes will pop up a dialog box in the browser to display the text in the string. This is the function call.

It can be found that function calling is very simple, just like learning at ordinary times. The key here is that in function calling mode, the this keyword in the function refers to a global object, if it is a window object in the browser. For example:
Copy codeThe Code is as follows:
Var func = function (){
Alert (this );
};
Func ();
The [object Window] is displayed.

Ii. method call mode

The function call mode is simple and the most basic method of calling. But it is also a function. After assigning a value to a member of an object, it will be different. After assigning a function to a member of an object, this is not called a function, but a method. For example:
Copy codeThe Code is as follows:
// Define a function
Var func = function (){
Alert ("Am I a function? ");
};
// Assign a value to an object
Var o = {};
O. fn = func; // do not enclose parentheses here
// Call
O. fn ();
In this case, o. fn is a method, not a function. In fact, the fn method body is exactly the same as func, but there is a subtle difference here. See the following code:
Copy codeThe Code is as follows:
// Connect the following code:
Alert (o. fn = func );
The printed result is true, which indicates that the two functions are the same, but modify the code of the function:

// Modify the function body
Var func = function (){
Alert (this );
};
Var o = {};
O. fn = func;
// Compare
Alert (o. fn = func );
// Call
Func ();
O. fn ();
The running result here is that the two functions are the same, so the printed result is true. However, because the call of the two functions is different, the call of func prints [object Window], while the result of o. fn is [object Object object].

This is the difference between function call and method call. In function call, this refers to the Global Object window, while in method, this refers to the current object, that is, o. this In fn refers to object o.

Iii. constructor call mode

This is also a function. In simple function mode, this indicates window. In object method mode, this indicates the current object. In addition to these two cases, functions in JavaScript can also be constructors. The syntax used to use a function as the constructor is to add a new keyword before the function call. Such as code:
Copy codeThe Code is as follows:
// Define a constructor
Var Person = function (){
This. name = "programmer ";
This. sayHello = function (){
Alert ("Hello, here is" + this. name );
};
};
// Call the constructor to create an object
Var p = new Person ();
// Use Object
P. sayHello ();
In the above case, first create a constructor Person and then use the constructor to create the object p. The new syntax is used here. Then, the sayHello () method is called using the object. This example uses constructors to create objects. From the case, we can see that this refers to the object itself. In addition to the simple usage above, there are several changes to the function as the constructor:

1. All attributes that need to be used by the object must use this Guide;

2. The meaning of the return Statement of the function is rewritten. If a non-object is returned, this is returned.

This in the constructor

We need to analyze the process of object creation to understand the meaning of this. The following code is used:
Copy codeThe Code is as follows:
Var Person = function (){
This. name = "programmer ";
};
Var p = new Person ();
The Person function is defined first. The execution is analyzed as follows:

1. When the program executes this sentence, it will not execute the function body. Therefore, the JavaScript interpreter does not know the content of this function.

2. Execute the new Keyword, create an object, open the interpreter memory, get the object reference, and hand over the reference of the new object to the function.

3. Execute the function and assign the passed object reference to this. That is to say, in the constructor, this is the object just created by new.

4. Add a Member for this, that is, add a member for the object.

5. When the function ends, return this and hand this to the variable on the left.

After the execution of the constructor is analyzed, we can see that this in the constructor is the current object.

Return in Constructor

The meaning of return changes in the constructor. First, if an object is returned in the constructor, the original intention is retained. If the returned result is a non-object, such as a number, Boolean, or string, this is returned. If there is no return statement, this is returned. See the following code:
Copy codeThe Code is as follows:
// Return the return of an object
Var ctr = function (){
This. name = "Zhao Xiaohu ";
Return {
Name: "Niu Liangliang"
};
};
// Create an object
Var p = new ctr ();
// Access the name attribute
Alert (p. name );
Run the code. The result is "niu Liangliang ". Because an object is returned in the constructor, the meaning of return is retained. The returned content is the object after return. Then, let's look at the following code:
Copy codeThe Code is as follows:
// Define the constructor that returns non-Object Data
Var ctr = function (){
This. name = "Zhao Xiaohu ";
Return "Niu Liangliang ";
};
// Create an object
Var p = new ctr ();
// Use
Alert (p );
Alert (p. name );
The code execution result is that the [object Object] is printed in a pop-up window, and then "Zhao Xiaohu" is printed. Because the return is a string of the basic type, the return statement here is invalid, the returned result is the this object. Therefore, the first print is [Object object], and the second does not print undefined.

Iv. apply call mode

In addition to the preceding three call modes, functions can also be used as objects using the apply and call methods. This is the fourth call mode, which I call as the apply mode.

First, we will introduce the apply mode. First, the apply mode can be used like a function or a method. It can be said that it is a flexible way to use it. First look at the Syntax: function name. apply (object, parameter array );

The syntax is rather obscure here, or the use cases are described as follows:

1. Create two js files: "js1.js" and "js2.js ";

2. Add code
Copy codeThe Code is as follows:
// In the js1.js File
Var func1 = function (){
This. name = "programmer ";
};
Func1.apply (null );
Alert (name );

// Js2.js File
Var func2 = function (){
This. name = "programmer ";
};
Var o = {};
Func2.apply (o );
Alert (o. name );

3. Run two sections of Code respectively. You can find that the name attribute in the first file has been loaded into the Global Object window. The name attribute in the second file is in the input object o, that is, the first is equivalent to function call, and the second is equivalent to method call.

The parameters here are the parameters included in the method, but they need to be stored in an array, such as code:
Copy codeThe Code is as follows:
// An array example
Var arr1 = [, 3, [], [, 8];
// Expand it
Var arr2 = arr1.conact. apply ([], arr1 );
Next, we will introduce the call mode. The biggest difference between the call mode and the apply mode is that the parameters in the call do not use arrays. The following code is clear:

// Define the Method
Var func = function (name, age, sex ){
This. name = name;
This. age = age;
This. sex = sex;
};
// Create an object
Var o = {};
// Add members to an object
// Apply Mode
Var p1 = func. apply (o, ["Zhao Xiaohu", 19, "male"]);
// Call mode
Var p2 = func. call (o, "Zhao Xiaohu", 19, "male ");

In the above Code, the results of the apply and call modes are the same.

In fact, the apply mode and call mode can be used to control the meaning of this, which is widely used in the design mode of function js. To sum up, there are four function calling modes in js: function, method, constructor, and apply. in these modes, the meaning of this is: in the function, this is the Global Object window. In the method, this refers to the current object. In the constructor, this is the created object, in apply mode, this can be specified at will .. If null is used in the apply mode, it is the function mode. If an object is used, it is the method mode.

5. Comprehensive examples

The following is a case study to end this article. Case study: There is a div with the id dv. Move the mouse above to increase the height by 2 times, move the mouse away to restore, and directly upload the js Code below:
Copy codeThe Code is as follows:
Var dv = document. getElementById ("dv ");
Var height = parseInt (dv. style. height | dv. offsetHeight );
Var intervalId;
Dv. onmouseover = function (){
// Stop an animation that has been executed
ClearInterval (intervalId );
// Obtain the Target Height
Var toHeight = height * 2;
// Obtain the current object
Var that = this;
// Open timer, slow change
IntervalId = setInterval (function (){
// Get the current height
Var height = parseInt (dv. style. height | dv. offsetHeight );
// Record the step size to be changed each time
Var h = Math. ceil (Math. abs (height-toHeight)/10 );
// Determines the change. If the step size is 0, the timer is stopped.
If (h> 0 ){
// Why is that used here? Think about it
That. style. height = (height + h) + "px ";
} Else {
ClearInterval (intervalId );
}
}, 20 );
};
Dv. onmouseout = function (){
// Same principle as before
ClearInterval (intervalId );
Var toHeight = height;
Var that = this;
IntervalId = setInterval (function (){
Var height = parseInt (dv. style. height | dv. offsetHeight );
Var h = Math. ceil (Math. abs (height-toHeight)/10 );
If (h> 0 ){
That. style. height = (height-h) + "px ";
} Else {
ClearInterval (intervalId );
}
}, 20 );
};

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.