


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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

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

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
