Home Web Front-end JS Tutorial Explanation of common JS function issues

Explanation of common JS function issues

May 21, 2018 am 10:54 AM
javascript js function

We often encounter Javascript function problems while studying, and this article will explain them.

What is the difference between function declaration and function expression

Function expression and function declaration statement contain the same function name, and both create new function objects. Their difference mainly lies in variable promotion The objects are different

The function name declared by the function is a variable, and the variable points to the function object. Variable promotion is the variable and function body of the function.

The function expression is assigned through var, and the entire function is assigned to a new variable. The variable is promoted to a new variable name, and the function initialization code will remain in its original position.

What is variable declaration prefix? What is the declaration prefix of a function

The declaration prefix of a variable

console.log(a);var a = 1;
结果为underfined
Copy after login

The declaration prefix of a variable will default to this code:

var a; //Before the variable declaration Set console.log(a);
a = 1;

The declaration of the function is preceded

a()function a(){console.log ("hello") }
Copy after login

The declaration of the function is preceded. The default code is:

function a(){                   //将函数声明提升console.log ("hello") }a()
arguments 是什么
Copy after login

arguments is an array-like object, which stores the parameters passed in when the function is executed. In the function, arguments can be used to obtain the parameters of all functions.
The following code:

function say(name,sex,age){  console.log(arguments);
}console.log('name:jiuyi',"sex:男",'age:54')
结果为:"name:jiuyi""sex:男""age:54"
Copy after login

How to implement function overloading

There is no concept of function overloading in JS. The subsequent new function will overwrite the previous function with the same name, even if the parameters are different .

      function p(a,b,c) {  
           console.log(a+b+c);  
       }  
 
       function p(a,b) {  
           console.log(a+b);  
       }       console.log(p('hello','jiuyi','yes'));       console.log(p('hello'))
结果为:  "hellojiuyi"
 "helloundefined"
Copy after login

As can be seen from the above figure, the latter P function overwrites the upper P function.

What is the immediate execution function expression? What is the function

Immediately executing a function expression means enclosing the entire function declaration with () to become a function expression, and then following the parameters, the function will be executed immediately.
function ( ){ }The function declaration is converted to ( function (){ }) ( )
Function:

Generates its own scope and independent local variables, without being disturbed by variable promotion. Reduce the possibility of conflicts between internal variables and external variables. The variables will be destroyed once executed.

What is the scope chain of a function

In JS, it is divided into global variables and local variables. Global variables can be accessed inside the function, but local variables inside the function cannot be accessed outside the function. In variables When inside a function, it will first search whether the variable is defined in this scope. If not, it will search to the next level until it finds the required variable. If it is not found in the global variable, an error will be reported. Try to use local variables to avoid interference with external variables.

1. Code output

  function getInfo(name, age, sex){        console.log('name:',name);        console.log('age:', age);        console.log('sex:', sex);        console.log(arguments); //代表实际参数,所以输出实际参数内容
        arguments[0] = 'valley';//name赋值为valley
        console.log('name', name);//所以这里参数输出为valley
    }
    getInfo('hunger', 28, '男');
    getInfo('hunger', 28);
    getInfo('男');
结果为:
name: hunger
 age: 28
 sex: 男
["hunger", 28, "男"]
name valley
 name: hunger
 age: 28sex: undefined
 ["hunger", 28]
 name valley
name: 男
age: undefined
 sex: undefined["男"]
name valley
Copy after login

2. Write a function that returns the sum of the squares of the parameters

  function sumOfSquares(){   var x = 0;   for(var i = 0;i<arguments.length;i++){
   x = x + arguments[i]*arguments[i]
   }   console.log(x)
   }
   sumOfSquares(2,3,4);   
   sumOfSquares(1,3);
结果为:2910
Copy after login

3. What is the output of the following code? Why

console.log(a); //The output is underfined, because JS will promote global variables, a only declares but does not assign a value var a = 1;console.log(b);//An error is reported because b Undeclared Unassigned

4. What is the output of the following code? Why

sayName(&#39;world&#39;); 
sayAge(10); function sayName(name){ console.log(&#39;hello &#39;, name);
 } var sayAge = function(age){ 
console.log(age); 
};
Copy after login

The result is:
hello world //Because the function declaration prefix function sayName(name) is promoted to the top, sayName has a declaration and content. Error report //Because the variable declaration preceded var sayAge is raised to the top, and the sayAge function is not declared, an error is reported.

5. What is the output of the following code? Why

function fn(){} 
 var fn = 3; console.log(fn);
相当于:  var fn;  function fn(){} ;
  fn = 3;  console.log(fn);    //所以输出为3
Copy after login

6.The output of the following code? Why

function fn(fn2){   console.log(fn2);   //输出 function fn2(){ console.log(&#39;fnnn2&#39;);}
   var fn2 = 3;   console.log(fn2);   //输出3
   console.log(fn);    //输出 function fn(fn2){ console.log(fn2); var fn2 = 3; console.log(fn2); console.log(fn); function fn2(){ console.log(&#39;fnnn2&#39;); } } fn(10);
   function fn2(){ 
     console.log(&#39;fnnn2&#39;);  //不输出,函数未调用
   } 
} 
fn(10);
相当于:var fn2;                            //声明前置function fn(fn2){  
   function fn2(){                   //函数声明前置
     console.log(&#39;fnnn2&#39;);          //此函数不输出,未调用
   } 
   console.log(fn2);               // 调用的其实是函数fn2
   fn2 = 3;             
   console.log(fn2);            // 此时fn2已被赋值为3
   console.log(fn);              //调用的其实是fn整个函数}
fn(10);
Copy after login

7.The output of the following code? Why

  var fn = 1;    function fn(fn){         console.log(fn);
    }    console.log(fn(fn));       //结果报错,变量提升,fn为1,直接调用1出错结果相当于:    var fn;    function fn(fn){         console.log(fn);
    }
    fn = 1;    console.log(fn(fn));
Copy after login

8.The output of the following code? Why

console.log(j);   //变量提升输出undefined
 console.log(i);    //变量提升输出undefinedfor(var i=0; i<10; i++){   //i循环后结果为10var j = 100; 
} console.log(i);    //输出10
 console.log(j);    //输出100
Copy after login

9.The output of the following code? Why

 fn();   var i = 10;   var fn = 20;   console.log(i);   function fn(){       console.log(i);       var i = 99;
       fn2();       console.log(i);       function fn2(){
           i = 100;
        }
    }
代码相当于:var i; 
var fn;function fn(){  
  var i ;  function fn2(){
  i = 100;
  } console.log(i);    //只有声明未赋值输出underfined
  i = 99;
  fn2();                  //经过运行I=100
  console.log(i);      //输出100}
fn();
i = 10;
fn = 20;console.log(i);             //输出10
Copy after login

10.The output of the following code? Why is the

 var say = 0;
    (function say(n){        console.log(n);        if(n<3) return;
        say(n-1);
    }( 10 ));    console.log(say);
Copy after login

code equivalent to: var say;

   (function say(n){        console.log(n);        if(n<3) return;    
        say(n-1);
    }( 10 ));
      say = 0;    console.log(say);           //输出为0结果为:10987654320
Copy after login

The function say is an immediate execution function, and the execution results are 10, 9, 8, 7, 6, 5, 4, 3 , 2. Finally, say is assigned a value of 0, so the output is 0

This article explains common js function problems. For more related content, please pay attention to the PHP Chinese website.

Related recommendations:

Explanation of JavaScript related functions

Explanation of jquery DOM& events

Some related modular basics

The above is the detailed content of Explanation of common JS function issues. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles