Home > Web Front-end > JS Tutorial > body text

Detailed explanation of 4 calling methods of JavaScript functions_javascript skills

WBOY
Release: 2016-05-16 16:51:44
Original
1055 people have browsed it

In JavaScript, functions are first-class citizens. Functions are a data type in JavaScript, not just used as a module like C# or other descriptive languages. There are four calling modes for functions, namely: function calling form, method calling form, constructor form, and apply form. Among all the calling modes here, the main difference lies in the meaning of the keyword this. These calling forms are introduced below.

Main content of this article:

1. Analyze the four calling forms of functions
2. Clarify the meaning of this in the function
3. Clarify the process of constructing function objects
4. Learn to use context to call functions

1. Function calling form

The function call form is the most common form and the best understood form. The so-called function form means that you generally declare a function and call it directly. For example:

Copy code The code is as follows:

// Declare a function and call
function func() {
alert("Hello World");
}
func();

or:
Copy code The code is as follows:

// Define the function using the Lambda expression of the function, and then call
var func = function() {
alert("Hello, programmer");
};
func();

These two pieces of code will pop up a dialog box in the browser to display the text in the string. This is a function call.

You can find that function calling is very simple, just like what you usually learn. The key here is that in the function calling mode, the this keyword in the function refers to the global object, which is the window object in the browser. For example:

Copy code The code is as follows:

var func = function() {
alert(this);
};
func();

At this time, a dialog box will pop up and print out [object Window].

2. Method calling mode

The function calling mode is very simple and is the most basic calling method. But it's the same function, but it's different after assigning it to a member of an object. After assigning a function to a member of an object, it is no longer called a function, but a method. For example:

Copy code The code is as follows:

// Define a function
var func = function() {
alert("Am I a function?");
};
// Assign it to an object
var o = {};
o. fn = func; // Be careful not to add parentheses here
// Call
o.fn();

At this time, o.fn is a method, not a function. In fact, the method body of fn is exactly the same as that of func, but there is a subtle difference here. Look at the code below:
Copy the code The code is as follows:

// Continue the above code
alert(o.fn === func);
The printed result is true, which indicates that the two functions are the same thing, 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();


Run here As a result, both functions are identical, so the printed result is true. However, since the calls of the two functions are different, the call of func prints [object Window], while the print result of o.fn is [object Object].

Here is the difference between function call and method call. In function call, this refers specifically to the global object window, while in method this refers specifically to the current object, that is, this in o.fn refers to the object o.

3. Constructor calling mode

It is also a function. In pure function mode, this refers to window; in object method mode, this refers to the current object. In addition to these two cases, functions in JavaScript can also be constructors. The syntax for using a function as a constructor is to precede the function call with the new keyword. For example, the code:

Copy the code The code is as follows:

// Define a constructor
var Person = function() {
this.name = "Programmer";
this.sayHello = function() {
alert( "Hello, this is" this.name);
};
};
// Call the constructor and create the object
var p = new Person();
// Use Object
p.sayHello();

The above case first creates a constructor Person, and then uses the constructor to create the object p. New syntax is used here. Then use the object to call the sayHello() method. This case of using a constructor to create an object is relatively simple. As you can see from the case, this refers to the object itself. In addition to the simple use above, there are several changes to functions as constructors, namely:

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

2. The meaning of the return statement of the function has been rewritten. If a non-object is returned, this will be returned.

this

in constructor

We need to analyze the process of creating objects to know the meaning of this. For example, the following code:

Copy the code The code is as follows:

var Person = function() {
This.name = "Programmer";
};
var p = new Person();

The function Person is first defined here. Let’s analyze the entire execution:

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

2. Next, execute the new keyword to create an object. The interpreter allocates memory, gets a reference to the object, and hands the reference to the new object to the function.

3. Then execute the function and hand the passed object reference to this. In other words, in the constructor, this is the object just created by new.

4. Then add members to this, that is, add members to the object.

5. Finally, the function ends, returns this, and hands this to the variable on the left.

After analyzing the execution of the constructor, we can get that this in the constructor is the current object.

return

in constructor

The meaning of return in the constructor has changed. First, if in the constructor, if an object is returned, then the original meaning is retained. If a non-object is returned, such as numbers, Boolean and strings, then this is returned. If there is no return statement, then this is also returned. See the following code:

Copy code The code is as follows:

// Return an object return
var ctr = function() {
this.name = "Zhao Xiaohu";
return {
name:"Niu Liangliang"
};
};
//Create object
var p = new ctr();
//Access name attribute
alert(p.name);

Execute the code, and the result printed here is "Niu Liangliang". Because the constructor returns an object, the meaning of return is retained, and the returned content is the object after return. Look at the following code:
Copy code The code is as follows:

// Define the constructor that returns non-object data
var ctr = function() {
This.name = "Zhao Xiaohu";
Return "Niu Liangliang";
};
// Create object
var p = new ctr();
// Use
alert(p);
alert(p. name);

The result of running the code is that the pop-up window first prints [object Object], and then prints "Zhao Xiaohu". Because the return here is a string, which belongs to the basic type, then the return statement here is invalid and returns is this object, so the first one prints [object Object] and the second one does not print undefined.

4. Apply calling mode

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

First introduce the apply mode. First of all, the apply mode can be used like a function or a method. It can be said to be a flexible usage method. First, let’s take a look at the syntax: function name.apply(object, parameter array);

The syntax here is rather obscure, so let’s use examples to illustrate:

1. Create two new js files, namely "js1.js" and "js2.js";

2. Add code

Copy code The code is as follows:

// In 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. When running two pieces of code respectively, you can find that the name attribute in the first file has been loaded into the global object window; while the name attribute in the second file is in the incoming object o, that is, the One is equivalent to a function call, and the second is equivalent to a method call.

The parameters here are the parameters of the method itself, but they need to be stored in the form of an array. For example, the code:

Copy the code The code is as follows:

// An example of an array
var arr1 = [1,2,3,[4,5],[6,7,8]];
// Expand it
var arr2 = arr1.conact.apply([], arr1);
Then introduce the call mode. The biggest difference between call mode and apply mode is that the parameters in call do not use arrays. See The following code will make it clear:

// Define method
var func = function(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
};
//Create object
var o = {};
//Add members to object
// apply pattern
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 apply mode and call mode are the same.

In fact, using apply mode and call mode, you can control the meaning of this in any way, and they are widely used in the design mode of function js. To briefly summarize, there are four modes of function calling in js, namely: functional, 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 refers to the created object. In the apply mode, this can be specified arbitrarily. If null is used in the apply pattern, it is a function pattern, and if an object is used, it is a method pattern.

5. Comprehensive examples

Let’s end this article with a case. Case description: There is a div with the id dv. When the mouse is moved above it, the height increases by 2 times. When the mouse leaves, the height will be restored. The js code is directly loaded below:

Copy code The code is as follows:

var dv = document.getElementById("dv");
var height = parseInt(dv.style.height || dv.offsetHeight);
var intervalId;
dv.onmouseover = function() {
// Stop the animation that is already executing
clearInterval(intervalId);
// Get the target height
var toHeight = height * 2;
// Get the current object
var that = this;
// Start the timer, change slowly
intervalId = setInterval(function() {
// Get the current height
var height = parseInt(dv. style.height || dv.offsetHeight);
                                                                                          Record the step size that needs to be changed each time                                                                                                                                                 Determine the change and stop the timer if the step size is 0
if( h > 0 ) {
) "px";
} else {
                                                                                                                                   // The principle is the same 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 {
                                                                             🎜>
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!