简体   繁体   中英

How can a javascript function, called with single argument, can call function with varying arguments?

I am working on a php application, in which I have the following existing code:

<ul>
   <li><a href="#" id="BillingP" onClick="change_main_Selection(this);">Paper</a></li>
   <li><a href="#" id="BillingE" onClick="change_main_Selection(this);">Electronic</a></li>
   <li><a href="#" id="BillingE" onClick="change_main_Selection(this,'CLHReports');">Clearing House Reports</a></li>
   <li><a href="#" id="BillingCP" onClick="change_main_Selection(this);">Capitation</a></li>
</ul>

As you can see function change_main_Selection(this) gets called, when user clicks on tab. I have tried to find change_main_Selection() definition and found following:

function change_main_Selection(main_tab, sub_tab, redirect_url, flgNc, onload){
    var main_tab_obj = main_tab;
    var sub_tab_obj = sub_tab;
}

My confusion is that while calling change_main_Selection(), it only takes single argument. But how can it call change_main_Selection() function with multiple arguments.

A JavaScript function does not perform any checking on parameter values (arguments).

If a function is called with missing arguments (less than declared), the missing values are set to: undefined

Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:

function myFunction(x, y) {
    y = y || 'defaultValue'; // overwrites falsey values (0, null, false)

    // better approach
    if (typeof y === 'undefined') { y = 'defaultValue'; }
}

With ES6, you can provide default values in a C++ style default values as follows:

function myFunction(x, y='defaultValue'){}

Javascript functions are called variadic functions. You can pass less params or more params . When you pass less params, extra params are set to undefined . If you pass more, you can see them in a special array like object called arguments .

See below example when you pass more arguments.

function sum() {
var s = 0;  
for(var i=0;i<arguments.length;i++){
        s+= arguments[i];
}
return s;
}

var ans = sum(1,2,3);
console.log(ans);//6

You can access to arguments by arguments variable inside your function as explained in w3schools this means there is no need to declare any parameter explicitly in your function:

 x = findMax(1, 123, 500, 115, 44, 88); console.info(x); function findMax() { var i; var max = -Infinity; for (i = 0; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } return max; } 

and you can access them by arguments variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM