Definition and invocation of the javascript-function

Source: Internet
Author: User

Defining functions

In JavaScript, you define a function as follows:

function abs(x) {    if (x >= 0) { return x; } else { return -x; }}

abs()the above functions are defined as follows:

    • functionIndicates that this is a function definition;
    • absis the name of the function;
    • (x)The parameters of the function are listed in parentheses, and multiple parameters are , separated;
    • { ... }The code between is a function body, can contain several statements, and even can not have any statements.

Note that when the statement inside the function body executes, the function executes and returns the result as soon as it is executed return . Therefore, it is possible to implement very complex logic within a function through conditional judgments and loops.

If there is no return statement, the result is returned after the function is executed, except for the result undefined .

Since the function of JavaScript is also an object, the abs() function defined above is actually a function object, and the functions name abs can be considered as a variable pointing to the function.

Therefore, the second way to define a function is as follows:

var abs = function (x) {    if (x >= 0) { return x; } else { return -x; }};

In this way, function (x) { ... } it is an anonymous function that does not have a function name. However, this anonymous function assigns a value to the variable abs , so abs the function can be called by a variable.

The two definitions are completely equivalent, and note that the second way is to add one at the end of the function body according to the complete syntax ; , indicating the end of the assignment statement.

Calling functions

When you call a function, you pass in the arguments sequentially:

abs(10); // 返回10abs(-9); // 返回9

Because JavaScript allows you to pass in any parameter without affecting the call, there is no problem with the parameters passed in that are more than the defined parameters, although they are not required inside the function:

abs(10, ‘blablabla‘); // 返回10abs(-9, ‘haha‘, ‘hehe‘, null); // 返回9

There is no problem with the parameters passed in that are less than defined:

// 返回NaN

abs(x)the parameters of the function are received at this time x undefined , and the computed result is NaN .

To avoid receipt undefined , you can check the parameters:

function abs(x) {    if (typeof x !== ‘number‘) { throw ‘Not a number‘; } if (x >= 0) { return x; } else { return -x; }}
Arguments

JavaScript also has a free keyword arguments that works only inside the function and always points to all parameters passed in by the caller of the current function. argumentssimilar Array but it is not a Array :

Using arguments , you can get all the parameters that the caller passed in. That is, even if the function does not define any parameters, it can get the value of the parameter:

function abs() {    if (arguments.length === 0) { return 0; } var x = arguments[0]; return x >= 0 ? x : -x;}abs(); // 0abs(10); // 10abs(-9); // 9

In fact arguments , it is most commonly used to determine the number of incoming parameters. You may see the following notation:

// foo(a[, b], c)// 接收2~3个参数,b是可选参数,如果只传2个参数,b默认为null:function foo(a, b, c) { if (arguments.length === 2) { // 实际拿到的参数是a和b,c为undefined c = b; // 把b赋给c b = null; // b变为默认值 } // ...}

To change the intermediate parameter to b an "optional" parameter, you can only pass the arguments judgment and then re-adjust the parameter and assign a value.

Rest parameters

Since JavaScript functions allow the receipt of arbitrary parameters, we have to use arguments them to get all the parameters:

function foo(a, b) {    var i, rest = []; if (arguments.length > 2) { for (i = 2; i<arguments.length; i++) { rest.push(arguments[i]); } } console.log(‘a = ‘ + a); console.log(‘b = ‘ + b); console.log(rest);}

In order to obtain a b parameters other than the defined parameters, we have to use arguments , and the loop to start from the index 2 to exclude the first two parameters, this is very awkward, just to obtain additional rest parameters, there is no better way?

The ES6 standard introduces the rest parameter, the function above can be rewritten as:

function foo(a, b, ...rest) {    console.log(‘a = ‘ + a); console.log(‘b = ‘ + b); console.log(rest);}foo(1, 2, 3, 4, 5);// 结果:// a = 1// b = 2// Array [ 3, 4, 5 ]foo(1);// 结果:// a = 1// b = undefined// Array []

The rest parameter can only be written at the end, preceded by the ... identification, from the running results, we know that the passed parameter is bound first, a b and the extra parameters are given to the variable in the array form, rest so we don't need to arguments get all the parameters.

It does not matter if the passed parameters are not filled with the normal defined parameters, and the rest parameter receives an empty array (note not undefined ).

Watch your return statement.

We talked about the JavaScript engine that has a mechanism for automatically adding semicolons at the end of the line, which may allow you to plant a large pit of the return statement:

function foo() {    return { name: ‘foo‘ };}foo(); // { name: ‘foo‘ }

If you split the return statement into two lines:

function foo() {    return { name: ‘foo‘ };}foo(); // undefined

Be careful, because the JavaScript engine automatically adds a semicolon mechanism at the end of the line, the code above actually becomes:

function foo() {    return; // 自动添加了分号,相当于return undefined; { name: ‘foo‘ }; // 这行语句已经没法执行到了}

So the correct multi-line notation is:

function foo() {    return { // 这里不会自动加分号,因为{表示语句尚未结束 name: ‘foo‘ };}

——————————————————————————————————————————————————
Source: https://www.liaoxuefeng.com/

Definition and invocation of the javascript-function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.