Home Web Front-end JS Tutorial Detailed explanation of JavaScript function object creation, parameters and scope instances

Detailed explanation of JavaScript function object creation, parameters and scope instances

Jul 25, 2017 am 11:29 AM
javascript js parameter

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 );
Copy after login

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));
Copy after login

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; 
}
Copy after login

Or:

var add = function(x, y){ 
return x + y; 
}
Copy after login

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";
Copy after login

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());
Copy after login

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 ()
Copy after login

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
Copy after login

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
Copy after login

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"));
Copy after login

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
Copy after login

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; 
} 
}
Copy after login

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; 
}
Copy after login

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();
Copy after login

What is the running result? Beginners are likely to get this answer:

global 
local
Copy after login

And the correct result should be:

undefined 
local
Copy after login

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!

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks 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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

i9-12900H parameter evaluation list i9-12900H parameter evaluation list Feb 23, 2024 am 09:25 AM

i9-12900H is a 14-core processor. The architecture and technology used are all new, and the threads are also very high. The overall work is excellent, and some parameters have been improved. It is particularly comprehensive and can bring users Excellent experience. i9-12900H parameter evaluation review: 1. i9-12900H is a 14-core processor, which adopts the q1 architecture and 24576kb process technology, and has been upgraded to 20 threads. 2. The maximum CPU frequency is 1.80! 5.00ghz, which mainly depends on the workload. 3. Compared with the price, it is very suitable. The price-performance ratio is very good, and it is very suitable for some partners who need normal use. i9-12900H parameter evaluation and performance running scores

C++ function parameter type safety check C++ function parameter type safety check Apr 19, 2024 pm 12:00 PM

C++ parameter type safety checking ensures that functions only accept values ​​of expected types through compile-time checks, run-time checks, and static assertions, preventing unexpected behavior and program crashes: Compile-time type checking: The compiler checks type compatibility. Runtime type checking: Use dynamic_cast to check type compatibility, and throw an exception if there is no match. Static assertion: Assert type conditions at compile time.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Advanced usage of reference parameters and pointer parameters in C++ functions Advanced usage of reference parameters and pointer parameters in C++ functions Apr 21, 2024 am 09:39 AM

Reference parameters in C++ functions (essentially variable aliases, modifying the reference modifies the original variable) and pointer parameters (storing the memory address of the original variable, modifying the variable by dereferencing the pointer) have different usages when passing and modifying variables. Reference parameters are often used to modify original variables (especially large structures) to avoid copy overhead when passed to constructors or assignment operators. Pointer parameters are used to flexibly point to memory locations, implement dynamic data structures, or pass null pointers to represent optional parameters.

Parameters of vlookup function and explanation of their meanings Parameters of vlookup function and explanation of their meanings Jan 09, 2024 pm 03:18 PM

We must have used the vlookup function when using excel. So there are several such functions, and how each function is used. As far as the editor knows, there are four vlookup functions, namely Lookup_value, Table_array, col_index_num, and Range_lookup. So let me tell you their specific usage~ The vlookup function has several parameters and the meaning of each parameter. The parameters of the vlookup function include Lookup_value, Table_array, col_index_num, and Range_lookup, a total of 4. 1.Lookup

See all articles