


Detailed explanation of JavaScript function object creation, parameters and scope instances
Function object
1.1 Create function
A not-so-used way to create a JavaScript function (almost no one uses it) is to act on Function through the new operator" "Constructor":
var funcName = new Function( [argname1, [... argnameN,]] body );
There can be as many parameters as you want in the parameter list, followed by the function body. For example:
var add = new Function("x", "y", "return(x+y)"); print(add(2, 4));
will print the result:
6
However, who would create a function in such a difficult-to-use way? If the function body is complex, it will take a lot of effort to splice the String, so JavaScript provides a kind of syntax sugar, that is, creating functions through literals:
function add(x, y){ return x + y; }
Or:
var add = function(x, y){ return x + y; }
In fact, such syntactic sugar is more likely to misunderstand programmers in traditional fields. The function keyword will call Function to new an object, and will The parameter list and function body are passed exactly to the Function constructor.
Generally speaking, declaring an object in the global scope (the scope will be introduced in detail in the next section) is just assigning a value to an attribute. For example, the add function in the above example actually just adds a value to the global object. An attribute is added, and the attribute name is add, and the value of the attribute is an object, that is, function(x, y){return x+y;}. It is important to understand this. The syntax of this statement is:
var str = "This is a string";
No difference. They all dynamically add a new attribute to the global object, that's all.
In order to illustrate that functions, like other objects, exist as an independent object in the JavaScript running system, we might as well look at this example:
function p(){ print("invoke p by ()"); } p.id = "func"; p.type = "function"; print(p); print(p.id+":"+p.type); print(p());
Nothing wrong, although p refers to an anonymous Function (object), but at the same time it can have attributes, exactly like other objects. The running results are as follows:
function (){ print("invoke p by ()"); } func:function invoke p by ()
1.2 Parameters of functions
In JavaScript, the parameters of functions are quite interesting. , for example, you can pass any number of parameters to a function, even if the function is declared without specifying formal parameters, for example:
function adPrint(str, len, option){ var s = str || "default"; var l = len || s.length; var o = option || "i"; s = s.substring(0, l); switch(o){ case "u": s = s.toUpperCase(); break; case "l": s = s.toLowerCase(); break; default: break; } print(s); } adPrint("Hello, world"); adPrint("Hello, world", 5); adPrint("Hello, world", 5, "l");//lower case adPrint("Hello, world", 5, "u");//upper case
The function adPrint accepts three formal parameters when declared: the string to be printed , the length to be printed, whether to convert to uppercase and lowercase markers. But when calling, we can pass one parameter, two parameters, or three parameters to adPrint in sequence (you can even pass it more than 3 parameters, it doesn’t matter). The running results are as follows:
Hello, world Hello hello HELLO
In fact, when JavaScript handles the parameters of a function, it is different from other compiled languages. What the interpreter passes to the function is an internal value similar to an array, called arguments. This is used when the function object is generated. Initialized. For example, when we pass one parameter to adPrint, the other two parameters are undefined. In this way, we can process those undefined parameters inside the adPrint function, which can be exposed to the outside: we can process any parameters.
Let’s discuss this magical arguments through another example:
function sum(){ var result = 0; for(var i = 0, len = arguments.length; i < len; i++){ var current = arguments[i]; if(isNaN(current)){ throw new Error("not a number exception"); }else{ result += current; } } return result; } print(sum(10, 20, 30, 40, 50)); print(sum(4, 8, 15, 16, 23, 42));//《迷失》上那串神奇的数字 print(sum("new"));
The function sum has no explicit formal parameters, and we can dynamically pass it any number of parameters, then, How to reference these parameters in the sum function? Here you need to use the pseudo array of arguments. The running results are as follows:
150 108 Error: not a number exception
Function scope
The concept of scope is used in almost all It is reflected in mainstream languages. In JavaScript, it has its particularity: the variable scope in JavaScript is valid within the function body, and there is no block scope. In Java language, we can define the subscript in the for loop block like this Variables:
public void method(){ for(int i = 0; i < obj1.length; i++){ //do something here; } //此时的i为未定义 for(int i = 0; i < obj2.length; i++){ //do something else; } }
And in JavaScript:
function func(){ for(var i = 0; i < array.length; i++){ //do something here. } //此时i仍然有值,及I == array.length print(i);//i == array.length; }
JavaScript functions run in the local scope, and the function body running in the local scope can access its outer ( may be global scope) variables and functions. The scope of JavaScript is lexical scope. The so-called lexical scope means that its scope is determined when it is defined (lexical analysis), not when executed, as in the following example:
var str = "global"; function scopeTest(){ print(str); var str = "local"; print(str); } scopeTest();
What is the running result? Beginners are likely to get this answer:
global local
And the correct result should be:
undefined local
Because in the function scopeTest In the definition, the undeclared variable str is accessed in advance, and then the str variable is initialized, so the first print(str) will return an undefined error. So why doesn't the function access the external str variable at this time? This is because, after the lexical analysis is completed, when constructing the scope chain, the var variable defined within the function will be put into the chain, so str is in the entire function scopeTest are all visible (from the first line to the last line of the function body). Since the str variable itself is undefined, the program is executed sequentially and will return undefined at the first line. The second line assigns a value to str, so the third line print(str) of the line will return "local".
The above is the detailed content of Detailed explanation of JavaScript function object creation, parameters and scope instances. For more information, please follow other related articles on the PHP Chinese website!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

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