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

伊谢尔伦
伊谢尔伦Original
2017-07-25 11:29:031344browse

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!

Statement:
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