Home >Web Front-end >JS Tutorial >Detailed explanation of how javascript uses functions and return value usage examples
In JavaScript, functions can
◆ be assigned to a variable
◆ be assigned to the properties of an object
◆ be passed into other functions as parameters
◆ be returned as the result of the function
Assign a value to a variable:
//声明一个函数,接受两个参数,返回其和 function add(x, y){ return x + y; } var a = 0; a = add;//将函数赋值给一个变量 var b = a(2, 3);//调用这个新的函数a print(b);
This code will print "5", because after the assignment, the variable a refers to the function add, that is, the value of a is a function Object (an executable code block), so you can use statements like a(2, 3) to perform sum operations.
Assignment to the properties of the object:
var obj = { id : "obj1" } obj.func = add;//赋值为obj对象的属性 obj.func(2, 3);//返回5
In fact, this example is essentially the same as the previous example. The a variable in the first example is actually the global object ( If in a client environment, represented as an attribute of 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 a parameter:
//高级打印函数的第二个版本 function adPrint2(str, handler){ print(handler(str)); } /将字符串转换为大写形式,并返回 function up(str){ return str.toUpperCase(); } //将字符串转换为小写形式,并返回 function low(str){ return str.toLowerCase(); } adPrint2("Hello, world", up); adPrint2("Hello, world", low);
Run this snippet, you can get the result:
HELLO, WORLD hello, world
It should be noted that the second parameter of the function adPrint2, the fact The above is a function. This processing function is passed in as a parameter. Within adPrint2, this function can still be called. This feature is useful in many places, especially when we want to process some objects, but are not sure. Regardless of the form in which it is processed, the "processing method" can be packaged as an abstract granularity (that is, a function).
As the return value of the function:
Let’s look at the simplest example first:
function currying(){ return function(){ print("curring"); } }
The function currying returns an anonymous function. This anonymous function will print "curring", a simple call currying() will get the following results:
function (){ print("curring"); }
If you want to call the anonymous function returned by currying, you need to do this:
currying()();
The first bracket operation means calling currying itself, the return value is a function at this time, and when the second bracket operator calls this return value, you will get the following result:
currying
The above is the detailed content of Detailed explanation of how javascript uses functions and return value usage examples. For more information, please follow other related articles on the PHP Chinese website!