Home > Web Front-end > JS Tutorial > Detailed explanation of basic functions for getting started with JavaScript_Basic knowledge

Detailed explanation of basic functions for getting started with JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 18:00:48
Original
743 people have browsed it

In general, functions in JavaScript can:

◆ be assigned to a variable

◆ be assigned to a property of an object

◆ be passed into something else as a parameter Function

◆ is returned as the result of the function

◆ Use literals to create

function objects

1.1 Creating functions

A trivial way to create a JavaScript function (almost no one uses it) is to use the new operator on the Function "constructor":

Copy code The code is as follows:
var funcName = new Function( [argname1, [... argnameN,]] body );

There can be any number of parameters in the parameter list, followed by the function body, for example:

Copy code Code As follows:
var add = new Function("x", "y", "return(x y)");
print(add(2, 4));

will The result will be printed:

6

However, who would create a function in such a difficult way? If the function body is complex, it will take a lot of effort to splice the String. So JavaScript provides a kind of syntactic sugar, which is to create functions through literals:

Copy code The code is as follows:
function add(x, y){
return x y;
}

or:

Copy Code The code is as follows:
var add = function(x, y){
return x y;
}

In fact, this is Syntactic sugar is more likely to misunderstand programmers in traditional fields. The function keyword will call Function to create a new object, and accurately pass the parameter list and function body to the Function's constructor.

Generally speaking, declaring an object in the global scope (scope will be introduced in detail in the next section) is nothing more than assigning a value to an attribute. For example, the add function in the above example actually just assigns a value to The global object adds an attribute. 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 follows:

Copy code The code is as follows:
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:

Copy code The code is as follows:
function p(){
print("invoke p by ()");
}

p.id = "func";
p.type = "function";

print(p);
print(p.id ":" p.type);
print(p());

That’s right. Although p refers to an anonymous function (object), it can also have attributes, just like other objects. The running results are as follows:

function (){
print("invoke p by ()");
}
func:function
invoke p by ()

1.2 Parameters of function

In JavaScript, function parameters 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, such as:

Copy code The code is as follows:
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, and whether to convert it to uppercase or lowercase marks. 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 function parameters, it is different from other compiled languages. What the interpreter passes to the function is something like The internal values ​​of the array are called arguments, which are initialized when the function object is generated. 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, and thus expose it to the outside: we can process any parameter.

We discuss this magical arguments through another example:

Copy code The code is as follows:
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));//The magical string of numbers on "Lost"
print(sum("new"));

The function sum has no explicit formal parameters, and we can Dynamically pass any number of parameters to it. So, 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 reflected in almost all mainstream languages. In JavaScript, it has its particularity: in JavaScript The variable scope is valid within the function body, without block scope. In Java language, we can define the subscript variable in the for loop block like this:

public void method(){
for( int i = 0; i < obj1.length; i ){
//do something here;
}
//i is undefined at this time
for(int i = 0; i < obj2.length; i ){
//do something else;
}
}
And in JavaScript:

Copy code The code is as follows:
function func(){
for(var i = 0; i < array.length; i ){
//do something here.
}
//At this time i still has a value, and I == array.length
print(i);//i == array.length;
}

JavaScript functions run in the local scope. The function body running in the local scope can access its outer (possibly 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:

Copy code The code is as follows:
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 definition of function scopeTest, the undeclared variable str is accessed in advance and then the str variable is initialized, 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".

Function context

In languages ​​such as Java or C/C, methods (functions) can only exist attached to objects and are not independent. In JavaScript, a function is also an object and is not part of any other object. It is particularly important to understand this, especially for understanding functional JavaScript. In functional programming languages, functions are considered first-class.

The context of a function can change. Therefore, this within the function can also change. The function can be used as a method of one object or as a method of another object at the same time. In short, the function itself is independent . The context of the function can be modified through the call or apply function on the Function object:

call and apply

call and apply are usually used to modify the context of the function. The this pointer will be replaced with the first parameter of call or apply. We might as well take a look at the examples in JavaScript Getting Started with Objects and JSON:

//Define a person named jack
var jack = {
name : "jack",
age : 26
}

//Define another person with the name abruzzi
var abruzzi = {
name : "abruzzi",
age : 26
}

//Define a global function object
function printName(){
return this.name;
}

//Set the context of printName to jack, and this at this time is jack
print(printName.call(jack));
//Set the context of printName to abruzzi, at this time this is abruzzi
print(printName.call(abruzzi));

print(printName.apply(jack));
print(printName.apply(abruzzi));
When there is only one parameter The usage of call and apply is the same, if there are multiple parameters:

setName.apply(jack, ["Jack Sept."]);
print(printName.apply(jack));

setName.call(abruzzi, "John Abruzzi");
print(printName.call(abruzzi));
The result is:

Jack Sept.
John Abruzzi
The second parameter of apply is an array of parameters required by a function, while call requires several parameters, separated by commas (,).

Using functions

As mentioned earlier, in JavaScript, functions can be assigned to a variable

◆ Assigned to the properties of the object

◆ Passed into other functions as parameters

◆ Returned as the result of the function

Let’s look at these scenarios respectively:

Assign a value to a variable:

//Declare a function that accepts two parameters and returns their sum
function add(x, y){
return x y;
}

var a = 0;
a = add;//Assign the function to a variable
var b = a(2, 3);//Call this new function a
print(b);
This code will print "5" because after the assignment, the variable a refers to the function add, that is to say, the value of a is a function object (an executable code block), so it can be used A statement like a(2, 3) is used to perform the sum operation.

is assigned to the attribute of the object:



Copy the code The code is as follows: var obj = {
id : "obj1"
}

obj.func = add;//Assign the value to the attribute of the obj object
obj.func(2, 3);// Return 5

In fact, this example is essentially the same as the previous example. The a variable in the first example is actually a property of the global object (if it is in the client environment, represented as the window object). The second example is the obj object. Since we rarely directly reference the global object, we will describe it separately.

passed as parameter:

//Second version of advanced printing function
function adPrint2(str, handler){
print(handler(str));
}

//Convert the string to uppercase and return
function up(str){
return str.toUpperCase();
}

/ /Convert the string to lowercase and return
function low(str){
return str.toLowerCase();
}

adPrint2("Hello, world", up) ;
adPrint2("Hello, world", low);
Run this snippet and you will get this result:

HELLO, WORLD
hello, world

should Note that the second parameter of the function adPrint2 is actually a function. If this processing function is passed in as a parameter, this function can still be called inside adPrint2. This feature is useful in many places, especially, When we want to process some objects, but are not sure in what form, we can wrap the "processing method" as an abstract granularity (ie, function).

as the return value of the function:

Let’s look at the simplest example first:

Copy code The code is as follows:
function currying(){
return function(){
print("curring");
}
}

The function currying returns an anonymous function. This anonymous function will print "curring". Simply calling currying() will get the following results:

Copy code The code is as follows:
function (){
print("curring");
}

If you want to call the anonymous returned by currying The function needs to be like this:

currying()();
The first bracket operation means calling currying itself. At this time, the return value is the function. The second bracket operator calls this return value, then You will get results like this:

currying
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template