Explanation of common JS function issues
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
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") }
The declaration of the function is preceded. The default code is:
function a(){ //将函数声明提升console.log ("hello") }a() arguments 是什么
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"
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"
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
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
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('world'); sayAge(10); function sayName(name){ console.log('hello ', name); } var sayAge = function(age){ console.log(age); };
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
6.The output of the following code? Why
function fn(fn2){ console.log(fn2); //输出 function fn2(){ console.log('fnnn2');} 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('fnnn2'); } } fn(10); function fn2(){ console.log('fnnn2'); //不输出,函数未调用 } } fn(10); 相当于:var fn2; //声明前置function fn(fn2){ function fn2(){ //函数声明前置 console.log('fnnn2'); //此函数不输出,未调用 } console.log(fn2); // 调用的其实是函数fn2 fn2 = 3; console.log(fn2); // 此时fn2已被赋值为3 console.log(fn); //调用的其实是fn整个函数} fn(10);
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));
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
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
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);
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
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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.

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

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.

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.

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.

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.

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.
