The function in JS

Source: Internet
Author: User

Function

    • Function
      • The function in JS
        • Create a function
        • Execute function
        • The core principle of function in JS
        • Formal parameters and arguments in a function
        • Arguments in a function
        • The return in the JS function
        • The anonymous function in JS
The function in JS

A function is a method of implementing a function
Also called subroutines, (in OOP) methods

Create a functionfunction name ( formal parameter ){function body (implementation of the specific JS code of the function)} Execute function function name () and execute the created function, and this function can execute many times each execution is equivalent to the function body in the implementation of the function of the JS code repeatedly executed again

In real projects, we typically encapsulate code that implements a specific function in a function
1, if the current page function needs to be executed multiple times in the page, not encapsulated into a function, each implementation of this function will need to re-write the code once, wasting time, and encapsulated in a function, in the future to achieve this function, we do not need to re-write the code, only need to re-execute the function, Improve the development efficiency.
2, encapsulated in a function, the page is basically difficult to duplicate the same code, reducing the redundancy of the Code in the page, improve the code reuse:低耦合高内聚

We make the above characteristics 函数封装 (OOP object-oriented programming idea, we need to grasp is the class of inheritance, encapsulation, polymorphism)

The core principle of function in JS

function as one of the reference data types in JS and is also operated by reference address

function fn () {var1+1console.log (num.tofixed (  2));} FN ()

    • Create a function
      • A function name is declared first in the current scope (the declared function name is the same as the variable name declared with Var: var sum; function sum () {}; These two names are duplicated)
      • The browser first opens up a new memory space (assigning a 16-based address), storing the code written in the function body as a normal string in the memory space (creating a function that does not make sense if it is not executed)
      • Assigns the address of the memory space to the previously declared function name
    • function Execution
      • Purpose: To implement the previously stored JS code to implement specific functions
      • 1, function execution, the browser will first open a new 私有作用域 (can only execute the function before the JS code written)
      • 2. Parameter Assignment
      • 3. Variable promotion in private scope
      • 4. Take those JS code strings that were stored at the time of creation to the private scope, and then turn them into JS expressions to execute from top to bottom
      • 5. Whether or not the private scope is destroyed

Closure Tip
function execution will form a private scope, let the inside of the private variables and the external complementary effects (mutual non-interference, the outside can not directly get the value of the variables inside), we can understand the private scope to protect the private variables, we call this protection mechanism closure

 

Stack memory

Scope (global scope/private scope): Provides an environment for JS code execution
堆内存
All reference data types, the content they need to store is in heap memory (equivalent to a warehouse to store information)

  • Objects store key-value pairs in the
  • The function stores the code as a string.
Formal parameters and arguments in a function

Formal parameters: Provide a portal, require the user to execute the function when the required values are passed in, the parameter is a variable, used to store and receive these values
Argument: The specific value passed to the parameter when the function is executed

1function sum (num1,num2) {//The num1,num2 here is shaped parametric (similar to Var)2 varTotal = Num1 +num23Total *=Ten4Total = Total.tofixed (2)5 console.log (total)6 }7Sum2,3)//the 2,3 here is the actual argument.8  9SumTen)//num1=10 num2=undefined defines a formal parameter but does not pass an argument at execution time, the value of the default argument is undefinedTen function sum (num1,num2) { One //- If a value is not passed, the operation gets the result of Nan, and to ensure that the result is not Nan, we set a default value of 0 for it . A //- fault-tolerant processing - //Mode 1 -NUM1 =typeofNUM1 = = ='undefined'? NUM1 =0: Num1 thenum2 =typeofnum2 = = ='undefined'? num2 =0: num2 - //Mode 2 -NUM1 = NUM1 | |0 -num2 = num2 | |0 +   - varTotal = Num1 +num2 +Total *=Ten ATotal = Total.tofixed (2) at console.log (total) - } -SumTen)//num1=10 num2=undefined defines a formal parameter but does not pass an argument at execution time, the value of the default argument is undefined

Small knowledge point for | | or operator
num2 = num2 | | 0 means: If num2 is null or undefined, the num2 is assigned a value of 0, otherwise num2 will not change. The purpose is to prevent num2 null or undefined errors.
Where: | | Representation or action, the first condition is true, the result is true without the need to execute the second condition, otherwise the second condition is executed, equivalent to the following code:

1 if (num2) {2 num2 = num2; 3 }else{40; 5 }

Arguments in a function

When we don't know how many values a user is going to pass (passing a few values), we can't set the number of formal parameters: we need to use the built-in argument collection of the function when we encounter such a requirement arguments
1. Arguments only functions
2, regardless of the execution of the function when the argument is passed, arguments is born, there is no pass argument Arg is an empty collection, passed the argument, ARG contains all the passed argument values.
3. All argument information is always stored in ARG, regardless of whether a formal parameter is set

1 function fn () {2for (var0; i < arguments.length; i++) {3  Console.log (arguments[i])4}5}6 fn (1 ,2,3,4,5,6)

Arguments is a collection of class arrays
features
1. Index as a number (name), starting from 0
Arguments[0]
ARGUMENTS[1]
2, has a length attribute, which stores the length of the current number of arguments (the number of actual arguments passed)
Arguments.length
arguments[' length ']

Arguments.callee stores the current function itself
Arguments.callee.caller stores where the current function executes (the host function), and the result of execution at the global scope is NULL
Arguments.callee and Arguments.callee.caller are rarely used in real projects, because in JS strict mode (use strict) we do not allow these two properties, and now most of the projects are based on strict mode

1 "Use Strict" //Add this sentence before the code is executed, and turn on the strict mode of JS2 function sum () {3Console.log (Arguments.callee.caller)//fn4 //Strict mode will error: uncaught TypeError: ' Caller ', ' callee ', and ' arguments ' properties may not be accessed on strict mode functio NS or the arguments objects for calls to them5 }6 function fn () {7SumTen, -,'Xiao Ming')8 }9FN ()

Sum of any number

1 function sum () {2 varTotal =NULL3  for(vari =0; i < arguments.length; i++){4 varCur =Number (Arguments[i]);5!isnan (cur)? Total + = cur:NULL;6 }7 console.log (total)8 }9SumTen, -,' -','ABC')

The return in the JS function

The protection mechanism of the closure causes the private scope to protect the private variables inside, so we cannot get the values of the variables inside the function.
The return value is an exit provided by the function: if we want to use some of the information that is private to the function outside, we need to return this information for external use.

1 function sum () {2 varTotal =NULL3  for(vari =0; i < arguments.length; i++){4 varCur =Number (Arguments[i]);5!isnan (cur)? Total + = cur:NULL;6 }7 returnTotal//Return is followed by values (values returned): Instead of returning the total variable, it returns the value stored in8 }9 varTotal= sum (Ten, -)//= = Outside the total in the global total and the total in the function is not necessarily connectedTenConsole.log (SUM (Ten, -,' -','ABC')) One //=>sum: Represents the function itself A //=>sum (): Let the function execute first, representing the result of the current return (what is behind the return, which is equivalent to what the function returns) - function fn () { - varTotal =0 the return -Console.log (total)//= = After a return is encountered in the function body, the code behind the return is not executed - } -Console.log (FN ())//= = If there is no return or return after the function, the result returned by default is undefined

The anonymous function in JS

A function without a name

  • function expression
Obox.onclick = function(){//To assign a function without a name (with a name) as a value to a variable or an event of an element, and so on, called a function expression .}
  • Self-executing functions
1 (function (n) {2// create function and execute function are put together, the creation completes immediately executes the word execution function 3 }) (ten) 4 // several ways to write a self-executing function: The symbol is just the control grammar specification 5 ;(function () {}) ()6 ~function () {} ()7 -function () {} ()8 +function () {} ()9 !function () {} ()

The function in JS

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.