Function usage in javascript

Source: Internet
Author: User

Function is used to define functions in js. Next I will introduce you to the usage of function Definition and related content such as passing values and function return values. For more information about function, see.

Functions in javascript can be used to create methods or classes. In fact, we can think of them as classes simulated by functions. (when it comes to classes, we generally need to understand the knowledge of closures ). Let's take a look at the method first.

Javascript Functions include famous functions, anonymous functions, and immediate execution functions extended based on anonymous functions.

A common function is a famous function directly declared by a function.

The Code is as follows: Copy code

 
Function Hello (){
Alert ("hello, everybody! ");
};

Hello ();

Function SayHelloTo (somebody ){
Alert ("hello," + somebody + "! ");
};

SayHelloTo ("James ");

The Hello and SayHelloTo methods are created. Hello is called directly through Hello () without parameters. The SayHelloTo method has a parameter. WHEN greeting someone, you need to know who is greeting. When SayHelloTo ("Zhang San") is called, a parameter is required. These codes are similar to java and C. There is a big change in method overloading. javascript itself does not support any overloading. A method name corresponds to a method. If multiple methods with the same name are forcibly written, the first method will be overwritten.

The Code is as follows: Copy code

Function Hello (){
Alert ("hello, everybody! ");
};

Hello ();

Function Hello (somebody ){
Alert ("hello," + somebody + "! ");
};

Hello ("James ");

The first Hello method is overwritten. If you call Hello () directly during execution, the second Hello method is called but no parameter value is passed. Therefore, the undefined information is displayed. When you call Hello ("James"), the execution is completed normally. In fact, javascript can also be overloaded in some straightforward ways. Anyone who has learned C # will know that there is a params keyword, which can pass an indefinite number of parameters to the method. We can manually judge the parameter information and simulate the effect of similar overloading. In javascript, if you do not need any params keyword, You can naturally transfer any number of parameters. Function has an arguments attribute. You can think of it as an array, which stores all parameters in the order of passed parameters. That is to say, we can not declare the parameter name when defining the method.

The Code is as follows: Copy code

Function ShowArguments (){
Var args = "";
For (var I = 0; I <arguments. length; I ++ ){
Args + = arguments [I] + ",";
};
Alert (args. substr (0, args. length-1 ));
};

ShowArguments (1, 2, 3, 4, 5, 6, 7 );

 
Try to use argements to simulate the overload.

The Code is as follows: Copy code

Function Hello (){
If (arguments. length = 0 ){
Alert ("hello, everybody! ");
}
Else {
Alert ("hello," + arguments [0] + "! ");
};
};
Hello ();
Hello ("James ");

 
Based on the number of parameters.

The Code is as follows: Copy code

Function Increase (arg ){
If (typeof arg = "undefined "){
Alert ("Enter Parameters ");
}
If (typeof arg = "string "){
Alert (String. fromCharCode (arg. charCodeAt (0) + 1 ));
}
If (typeof arg = "number "){
Alert (arg + 1 );
}
};
Increase ();

Increase ("");
Increase (1 );

 
Based on the overload of different parameter types.
 
Functions can also be anonymous functions apart from well-known functions. Anonymous functions are functions without sub-names. They are all complete function objects, no matter whether they are well-known or have no sub-names. Anonymous functions are declared using functions, but they do not need to be specified. Other aspects, such as parameters, are no different from those of name functions.

The Code is as follows: Copy code

Function (){
......
};


Anonymous functions can generally meet the needs of temporary functions and do not need to be referenced by variables (a famous function can be considered as a function with variable reference ). For example, you can use anonymous functions to add events to an object by using a function as a value object as a parameter input method and programming method. Of course, you can declare variables separately to reference an anonymous function object, which is no different from a common famous function.

 

The Code is as follows: Copy code

Function Each (array, fun ){
For (var I = 0; I <array. length; I ++ ){
Fun (array [I]);
};
};
Var nums = [1, 2, 3, 4, 5, 6, 7];
Each (nums, function (arg ){
Alert (arg );
});

 

Run the code above and output the elements in the array in sequence.

The Code is as follows: Copy code

// Display the current time on the title when loading the form
Window. onload = function (){
Document. title = new Date (). toString ();
};

// You can also pass the anonymous method into the timer.
SetInterval (function (){
Document. title = new Date (). toString ();
},1000 );

 

Bind events and perform scheduled operations using anonymous functions.

 

The Code is as follows: Copy code

Var Hello = function (){
Alert ("hello, everybody! ");
};

 

If an anonymous function is assigned to a variable, it is no different from a normal function with a name. However, whether it is a variable reference or a common well-known function, such a function occupies a certain amount of resources permanently in the memory. Sometimes we only want to execute a function that does not need to be referenced. directly executing an anonymous function may be the best choice. Wrap the anonymous function and add a bracket for execution. Everything is OK. This is the immediate execution function extended by the anonymous function.

The Code is as follows: Copy code

 

(Function (){
Alert ("hello, everybody! ");
})();

(Function (somebody ){
Alert ("hello," + somebody + "! ");
}) ("James ");

 

Immediate function execution often has unexpected results in event binding and callback setting, which can solve such problems as object reference.

 

The Code is as follows: Copy code
Var student = {
Name: "James ",
Age: 20,
Introduce: function (){
Alert ("My Name is" + this. Name + ", this year" + this. Age + "years old! ");
}};
Window. onload = (function (obj) {return function () {obj. Introduce () ;}}) (student );

 

Because of these features of functions in javascript and the features of its objects, we can also write some programs with the meaning of functional. In fact, functions in javascript are really the boss.

The Code is as follows: Copy code

 

Function Sum (fun, x ){
If (x <= 0)
Return 0;
Return fun (x) + Sum (fun, x-1 );
};

Alert (Sum (function (I) {return I * I;}, 100 ));


Function parameters.


When the number of input parameters is less than the number of declared parameters, the missing parameter value is: undefined

The Code is as follows: Copy code

Function ReciveParam (/* First parameter */a,/* second parameter */B)
{
Alert ("a:" + a); // display: a: First Parameter
Alert ("B:" + B); // display: B: undefined
}

Function GiveParam ()
{
ReciveParam ("first parameter ");
}

 

2. You can use the arguments object in the function to obtain all the parameters of the function.

The Code is as follows: Copy code

Function show ()
{
Var largest = Max (56,123 );
Alert (largest); // display: 10000
}

Function Max (m)
{
Var re = 0;
For (var I = 0; I <arguments. length; I ++)
{
If (arguments [I]> re)
{
Re = arguments [I];
}
}

Return re;
}

The Arguments object is an object similar to an array. You can obtain all parameters based on the number of parameters rather than the name, and arguments also has the length attribute, which can be used to obtain the number of actual parameters.

Although arguments has some array features, it is not an array. In fact, arguments [] is two methods to reference the same variable as the actual parameter:

The Code is as follows: Copy code

Function ChangeParamValue ()
{
ChangParamValueDo ("first parameter", "second parameter ");
}

Function ChangParamValueDo (a, B)
{
Alert ("Before change: a:" + a + ", B:" + B); // display: Before change: a: first parameter, B: Second Parameter
Arguments [0] = "arguments0 ";
Arguments [1] = "arguments1 ";
Alert ("after changing with arguments: a:" + a + ", B:" + B); // display: After changing with arguments: a: arguments0, B: arguments0

}

Arguments has a callee attribute and does not reference the currently executed function.

The Code is as follows: Copy code

Function f (x)

{

If (x <= 1) return x;

Return x * arguments. callee (x-1 );

}

 

3. Use object attributes as parameters: you do not need to remember the order of parameters, and use the object attribute name to pass parameters.

The Code is as follows: Copy code

Function ArrayCopy (name, age, grade, sex, height, weiht)
{
Alert ("name:" + name + "age:" + age + "grade:" + grade + "sex:" + sex + "height:" + height + "weiht: "+ weiht );
}

Function EasyCopy (args)
{
ArrayCopy (args. name | "",
Args. age | 0,
Args. grade | "one ",
Args. sex | "optional ",
Args. height | 100,
Args. weight | 100)
}

Function show ()
{
EasyCopy ({name: 'lily', age: '13', grade: 'Three '});
EasyCopy ({name: 'mark', height: '000000', weight: 180 });
}

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.