4 ways to invoke JavaScript functions

Source: Internet
Author: User

In JavaScript, a function is a class citizen, and a function is a data type in JavaScript, not just as a module, as in C # or other descriptive languages. The function has four invocation patterns: function invocation form, method invocation form, constructor form, and apply form. The main difference in all of the invocation patterns here is the meaning of the keyword this, which is described in the following separate invocation forms.

The main content of this article:

1. Four invocation forms of analytic functions
2. Figuring out the meaning of this in the function
3. Defining the process of constructing a letter object
4. Learn to invoke functions using context

One, function call form

The function invocation form is the most common form and is also the best understood form. The so-called function form is the general declaration of functions directly after the call is. For example:

Copy CodeThe code is as follows:
Declares a function and calls the
function func () {
Alert ("Hello World");
}
Func ();


Or:

Copy CodeThe code is as follows:
Use the function's lambda expression to define the function, and then call the
var func = function () {
Alert ("Hello, programmer");
};
Func ();


Both of these codes pop up a dialog box in the browser that displays the text in the string, which is called by the function.

It can be found that the function call is very simple, is the usual learning, the key here is, in the function call pattern, the function of the This keyword refers to the global object, if in the browser is the Window object. For example:

Copy CodeThe code is as follows:
var func = function () {
alert (this);
};
Func ();


At this point, a dialog box pops up to print [object Window].

Second, method invocation mode

The function invocation pattern is simple and is the most basic way to call. But the same is true of functions, which are assigned to the members of an object and are not the same. After assigning a function to a member of an object, this is not called a function, but rather it is called a method. For example:

Copy CodeThe 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; Notice there's no parentheses here.
Call
O.fn ();


At this point, O.fn is the method, not the function. In fact, the method body of FN is exactly the same as func, but there is a subtle difference here. Look at the following code:

Copy CodeThe code is as follows:
Connect the code above
Alert (O.fn = = = func);
The print result is true, which indicates that two functions are the same thing, but modify the code of the function:

Modify function Body
var func = function () {
alert (this);
};
var o = {};
O.fn = func;
Comparison
Alert (O.fn = = = func);
Call
Func ();
O.fn ();


The result here is that two functions are the same, so the print result is true. However, because the invocation of two functions is not the same, the invocation of Func, which prints [object Window], and O.fn's printing result is [Object Object].

Here is the difference between a function call and a method call, where this refers to the Global object window, whereas in the method this is the reference to the current object, which is the object o in O.fn.

Third, constructor invocation pattern

The same is the function, in the simple function mode, this represents window; In object method mode, this refers to the current object. In addition to these two cases, a function in JavaScript can also be a constructor. The syntax for using a function as a constructor is to precede a function call with a new keyword. 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 the object
var p = new person ();
Working with objects
P.sayhello ();


The above case first creates a constructor person, and then uses the constructor to create the object p. This uses the new syntax. You then use the object to invoke the SayHello () method, which is a simple case of creating an object using the constructor. As you can see from the case, this refers to the object itself. In addition to the simple use above, the function as a constructor has several changes, namely:

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

2. The return statement meaning of the function is rewritten, and if a non-object is returned, this is returned.

This in the constructor

We need to analyze the process of creating objects in order to know the meaning of this. As in the following code:

Copy CodeThe code is as follows:
var person = function () {
this.name = "Programmer";
};
var p = new person ();


Here the function person is defined first and the entire execution is analyzed below:

1. When the program executes to this sentence, the function body is not executed, so the JavaScript interpreter does not know the contents of the function.

2. Next execute the New keyword, create the object, the interpreter opens up memory, gets the object's reference, and gives the new object a reference to the function.

3, immediately after the execution function, will pass over the object reference to this. That is, in the construction method, this is the object that was just created by new.

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

5, the last function ends, returns this, the this to the left of the variable.

After analyzing the execution of the constructor, it is possible to obtain that this is the current object in the constructor.

Return in the constructor

The meaning of return in the constructor has changed, first if in the constructor, if an object is returned, the original intent is preserved. If the returned non-object, such as number, Boolean, and string, then return this, if there is no return statement, then also return this, see the following code:

Copy CodeThe code is as follows:
Returns the return of an object
var ctr = function () {
THIS.name = "Chaohu";
return {
Name: "Neu Liangliang"
};
};
Creating objects
var p = new Ctr ();
Access the Name property
alert (p.name);


Executes the code, and the result here is "Neu Liangliang". Because an object is returned in the constructor, leave the meaning of return, return the object after return, and look at the following code:

Copy CodeThe code is as follows:
To define a constructor that returns non-object data
var ctr = function () {
THIS.name = "Chaohu";
Return "Neu Liangliang";
};
Creating objects
var p = new Ctr ();
Use
Alert (p);
alert (p.name);


The result of the code is that the pop-up window prints [object Object] and then prints "Chaohu" because the return is a string, which is a primitive type, then the return statement here is invalid and the This object is returned, so the first one to print is [object Object] and the second one does not print undefined.

Iv. Apply Invocation Mode

In addition to the above three invocation modes, the function as an object and the Apply method and the call method can be used, this is the fourth invocation pattern, I call it the Apply mode.

First introduce the Apply mode, first of all, here the Apply mode can be used as a function, or as a method to use, can be said to be a flexible way to use. First look at the syntax: function name. Apply (object, array of arguments);

Here to see the syntax is more obscure, or use a case to illustrate:

1, new two JS files, respectively, "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, running two pieces of code, you can find that the first file name property has been loaded into the Global object window, and the second file name property is in the Incoming object o, that is, the first equivalent of a function call, the second 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, such as code:

Copy CodeThe code is as follows:
An example of an array
var arr1 = [1,2,3,[4,5],[6,7,8]];
To expand it
var arr2 = Arr1.conact.apply ([], arr1);
Then introduce the call mode, the most important difference between call mode and apply mode is that the parameters in call do not use arrays, see the following code is clear:

Defining methods
var func = function (name, age, Sex) {
THIS.name = name;
This.age = age;
This.sex = sex;
};
Creating objects
var o = {};
Add members to an object
Apply Mode
var p1 = func.apply (O, ["Chaohu", 19, "male"]);
Call mode
var P2 = func.call (o, "Chaohu", 19, "male");

The above code, the Apply mode and the call mode result is the same.

In fact, the use of Apply mode and call mode, you can control the meaning of this arbitrary operation, in the function of JS design pattern is widely used. A brief summary of the function calls in JS has four modes, namely: function, method, constructor and apply. In these patterns, the meaning of this is the Global object window in the function, in which this refers to the current object, in the constructor this is the The object that is created is optionally specified in the Apply mode. If NULL is used in the Apply mode, it is the function pattern, and if the object is used, it is the method pattern.

V. Comprehensive examples

Let's end this article with a case. Case Description: There is a div,id for DV, the mouse moved to the top to increase the height of twice times, the mouse left to recover, the following directly on the JS code:

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's already in execution
Clearinterval (Intervalid);
Get the target height
var toheight = height * 2;
Get current Object
var = this;
Opener Timer, slow change
Intervalid = setinterval (function () {
Get the height of the present
var height = parseint (dv.style.height | | dv.offsetheight);
Record the step size that needs to change every time
var h = Math.ceil (Math.Abs (height-toheight)/10);
Judging the change, stop the timer if the step is 0
if (H > 0) {
Why do you use that here? Think about it.
That.style.height = (height + h) + "px";
} else {
Clearinterval (Intervalid);
}
}, 20);
};
Dv.onmouseout = function () {
The principle is the same as before
Clearinterval (Intervalid);
var toheight = height;
var = 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);
};

4 ways to invoke JavaScript functions

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.