4 ways to invoke JavaScript functions _javascript tips

Source: Internet
Author: User
Tags abs object object setinterval

In JavaScript, a function is a first-class citizen, a function in JavaScript is a data type, not as a C # or other descriptive language just as a module to use. Functions have four invocation modes: function invocation form, method invocation form, constructor form, and apply form. In all of the invocation patterns here, the main difference is in the meaning of this keyword, which is described in the following ways.

The main content of this article:

1. Analysis function of four kinds of call form
2. Figure out the meaning of this in the function
3. Clarifying the process of constructing a Function object
4. Learn to use context to invoke functions

The form of function call

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

Copy Code code as follows:

Declare a function and call the
function func () {
Alert ("Hello World");
}
Func ();

Or:
Copy Code code as follows:

Use the function's lambda expression to define the function, and then call the
var func = function () {
Alert ("Hello, programmer");
};
Func ();

Both pieces of code pop a dialog box in the browser, displaying the text in the string, which is the function call.

You can find that the function call is very simple, is the same as normal learning, the key here is that in the function call mode, the function of the This keyword refers to the global object, if in the browser is the Window object. For example:

Copy Code code as follows:

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

At this point, a dialog box pops up and prints out [object Window].

Second, method call mode

The function invocation pattern is very simple and is the most basic way to invoke it. But the same function, assigning it to a member of an object, is different. After assigning a function to a member of an object, this is not called a function, but rather a method. For example:

Copy Code code as follows:

Define a function
var func = function () {
Alert ("Am I a function?");
};
Assign it to an object
var o = {};
O.fn = func; Notice, don't add parentheses here.
Call
O.fn ();

At this point, O.fn is a method, not a function. The FN method is actually exactly the same as func, but there is a subtle difference. Look at the following code:
Copy Code code 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:

modifying function bodies
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. But since two function calls are not the same, Func calls, which print [object Window], and O.FN print results [object].

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

Third, constructor call pattern

The same function, in pure function mode, this represents window; In object method mode, this refers to the current object. In addition to both cases, a function in JavaScript can also be a constructor. The syntax for using a function as a constructor is to precede the function call with a new keyword. such as code:

Copy Code code as follows:

Define a constructor
var person = function () {
this.name = "Programmer";
This.sayhello = function () {
Alert ("Hello, here is" + this.name);
};
};
Call constructor, create 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. Here you use the new syntax. Then, using the object to invoke the SayHello () method, the case that uses the constructor to create the object is relatively simple. As you can see from the case, this refers to the object itself. In addition to the simple use above, functions as constructors have several changes, respectively:

1. All properties that need to be used by objects must be guided using this;

2, the function of the return statement meaning is overwritten, if returned to a non object, returns this.

This in the constructor

We need to analyze the process of creating objects before we know what this means. Like the following code:

Copy Code code as follows:

var person = function () {
this.name = "Programmer";
};
var p = new person ();

Here we first define the function person, and the following is an analysis of the entire execution:

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

2, next executes the new keyword, creates the object, the interpreter opens up the memory, obtains the object the reference, gives the new object the reference to the function.

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

4, and then add members to this, that is, add members to the object.

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

After parsing the execution of the constructor, you can get that this is the current object in the constructor.

Return in the constructor

The meaning of return is changed in the constructor, first, if you are returning an object in the constructor, then leave the original. If you return a non-object, such as a number, Boolean, and string, then return to this, and if there is no return statement, go back to this and look at the following code:

Copy Code code as follows:

Returns the return of an object
var ctr = function () {
THIS.name = "Chaohu";
return {
Name: "Neu Liangliang"
};
};
Creating objects
var p = new Ctr ();
Accessing the Name property
alert (p.name);

Executes the code, and the result printed here is "Neu Liangliang". Because the constructor returns an object, it retains the return meaning, returns the object after the return, and then looks at the following code:
Copy Code code as follows:

Define constructors that return 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 run is that the first window prints [object], and then prints "Chaohu", because here returns a string, which is a basic type, the return statement here is invalid and the This object is returned, so the first print is [object Object] and the second does not print undefined.

Iv. Apply Call Mode

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

Introduce the Apply mode first, here the Apply mode can be used as a function, also can be used as a method, can be said to be a flexible use method. First look at the syntax: the name of the function. Apply (object, array of parameters);

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

1, the new two JS files, respectively, "Js1.js" and "js2.js";

2, add code

Copy Code code 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 of the Name property has been loaded into the Global object window, and the second file of the Name property in the Incoming object o, that is, the first equivalent to a function call, the second equivalent to a method call.

The parameter here is the parameter that the method itself takes, but it needs to be stored in the form of an array, such as code:

Copy Code code 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 are not in the array, 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 a member 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 results are the same.

In fact, using the Apply mode and call mode, you can manipulate the meaning of this in any way, and it is widely used in the design pattern of the function JS. Simple summary, the function call in JS has four kinds of modes, these are: functional, method, constructor, and apply. And in these patterns, this means: In the function this is the Global Object window, in the method this is the current object, in the constructor this is The object being created, in the Apply mode this can be arbitrarily specified. Using NULL in the Apply mode is a function pattern, and if you use an object, it is a method pattern.

V. Synthesis of examples

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

Copy Code code as follows:

var dv = document.getElementById ("DV");
var height = parseint (dv.style.height | | dv.offsetheight);
var intervalid;
Dv.onmouseover = function () {
Stop an animation that is already in execution
Clearinterval (Intervalid);
Get the height of the target
var toheight = height * 2;
Get current Object
var that = 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 each time
var h = Math.ceil (Math.Abs (height-toheight)/10);
To determine the change, stop the timer if the step is 0
if (H > 0) {
Why do we use that? Think about it.
That.style.height = (height + h) + "px";
} else {
Clearinterval (Intervalid);
}
}, 20);
};
Dv.onmouseout = function () {
The 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);
};

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.