Small case-function that JavaScript should pay attention

Source: Internet
Author: User

Function functions are very important in Javascript. The "Object-Oriented" of JS we usually discuss is based on it. It can be said that we should be quite familiar with it, it stores many unique places.

 

Every function is a function-type instance.

First, let's understand this sentence: each function is actually a function-type instance. That is, what we declareFunctions are all objects and have their own attributes and methods. The function name is just a pointer to the object..

Let's look at the example below:

Function myfuc (ARG) {alert (ARG) ;}var anfuc = myfuc; myfuc = NULL; anfuc (1); // an error is reported, or is 1 displayed ??

 

The result is pop-up 1. myfuc is just a pointer to our function object. It points to null and does not affect anfuc. Therefore, the call is unaffected.

 

Internal Attributes of a function

Arguments and this: arguments are a class array object that contains all the parameters passed in when the function is called. You can use arguments [0], arguments [1]… In addition, it also has the attribute callee, which is also a pointer pointing to a function that owns the arguments object. This attribute is quite useful in recursion, it is easier to maintain and robust than direct function names.

   function myfuc(arg) {        if (arg <= 1) {            return 1;        } else {            return arg + myfuc(arg - 1);        }    }    function anfuc(arg) {        if (arg <= 1) {            return 1;        } else {            return arg + arguments.callee(arg - 1);        }    }

 

Although these two functions are written differently, they are for the same purpose. We strongly recommend the second method: to modify the function name at any time, you only need to modify the declaration, take a look at the example below.

VaR myfuc2 = myfuc; var anfuc2 = anfuc; myfuc = NULL; anfuc = NULL; alert (anfuc2 (3); // pop up 6 alert (myfuc2 (3 )); // No pop-up and an error is reported

 

In the call of myfuc2, we still look for the call of myfuc in recursion, but it has long been "Something is wrong". In anfuc2, arguments. callee always points to the currently called function, that is, anfuc2.

 

This attribute indicates the scope of the function execution. It is very important to understand its meaning correctly.

 

VaR name = "window"; function sayname () {alert (this. name);} var o = new object (); O. name = "object"; O. sayname = sayname; sayname (); // window o is displayed. sayname (); // The object is displayed.

 

Although sayname and O. sayname point to the same object, their calls output different results. We know that the declared global variables and functions belong to windows, which is actually equivalent to window. Name and window. sayname. This dynamically points to the object with this method.

 

Function Attributes and Methods

We just introduced the attributes that can be used within the function break. Since the function is an object, it certainly has the attributes and methods that can be used by us.

Length attribute: number of parameters to be accepted during function declaration.

Prototype attribute: This .. This .. This is where JS is powerful. It not only allows js to perfectly implement "Classes", but also has some object-oriented language features such as inheritance, extends the features and attributes that built-in objects do not have.

Apply method and call method: These two methods allow the function to "call itself", but the parameter passing method is different.

 

No heavy load

JS does not have heavy loads. Every attempt to overload will overwrite the previous function declaration. However, through JS features, we can implement some features similar to heavy loads. Because the function is an object, the Declaration is just a pointer to the object.When locating a function in JS, it only depends on the function name and does not consider the parameters you pass.Therefore, we can use the following two methods to implement similar overloading. These two methods are essentially the same, but they only differ in the form of representation.

1, arguments

Function sayhi () {var result = "default"; if (arguments [0]) {result = arguments [0];} If (arguments [1]) {result + = arguments [1];} If (arguments [2]) {result + = arguments [2];} If (arguments [3]) {result + = arguments [3];} // you can even traverse arguments to support the infinite parameter return result;} alert (sayhi ("")); // A alert (sayhi ("A", "B"); // AB alert (sayhi ("A", "B", "C ")); // ABC

 

From the call point of view, whether the overload is implemented.

2. Declare all parameters

Function sayhi (A, B, C/* can also be more */) {var result = "default"; if (a) {result = A;} If (B) {result + = B;} If (c) {result + = C;} // if there are other supported return results ;}

 

The call is the same and the result is the same.

 

The first method is more flexible, and the second method is easier to read and more friendly to callers. If there are not many recommended parameters, use the second method. To support unlimited parameters, use the first one. We recommend that you do not use both of them. This will make the code messy, and there will be a lot of trouble in maintenance and future expansion.

 

Function Creation Method

Generally, there are two ways to create a function:

1. function declaration method: function func (){}

2. function expression: var func = function (){}

 

Are these two forms just different ?? Of course not,When parsing JS, the parser processes the function declaration first and makes the function available before any code to be executed. function expressions are only executed to all rows, will be parsed and executed.

That is to say:

 sayHi();    function sayHi() {        alert("hi");    }

 

In this way, the code is okay and the HI will pop up.

However

sayHi();    var sayHi = function() {        alert("hi");    }

 

In this way, an error is reported and an object is missing.

 

Anonymous functions and closures

Anonymous functions are also called Lambda functions. In general, anonymous functions are used in the following situations:

1. Callback Function

2. function as return value

3. Plug-in development

As we often see:

(Function () {// code}) (); (function ($) {// code}) (jquery );

 

The second is the development method recommended by jquery. Here, an anonymous function is declared and then executed immediately. Declare variables and functions in a function. In addition to some variables and functions bound to global variables, we cannot access them outside of the system, which is isolated and does not affect the page, no closure exists internally. After the function is executed, the variable function will be recycled.

 

Many anonymous functions often see closures. What Are closures?

Let's look at an example:

Function createfunc () {var name = "123"; return function () {alert (name) ;}}var func = createfunc (); func (); // 123 is displayed

 

This is a simple example of a closure. createfunc returns an anonymous function. Generally, after a function is executed, its internal variables will be recycled, however, the functions returned by createfunc maintain reference to the internal variable name, because some functions can still be used as long as func exists, when createfunc is executed, the internal variables created are located in the memory. The names created by createfunc () will not be recycled until func = NULL is set.

 

A closure is a function that has the right to access another function scope variable.It will make the variables in another function still process valid states, which sometimes brings us great convenience, but we may sometimes consider the use of closures: because of the existence of closures, after the function is executed, all the internal variables cannot be recycled immediately and remain in the memory.

 

JS functions are unique and important. Using JS functions in other languages cannot reflect their power, and may be confused. It also makes JS powerful, so that JS has some advanced features such as encapsulation and inheritance, and is more conducive to the development of robust and easy-to-maintain applications.

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.