开发者

understanding javascript functions

I just have a small question that I would like some clarification about, if I have created a fu开发者_运维问答nction that is set up to accept 2 parameters and then perform some calculation but then I realise that the function I have created could also be used in another part of my code but will need to accept an additional parameter, how can use the function but pass in an additional parameter?

Regards Kyle


You basically create a function function with any number of parameters and call them by passing any number of parameters.

For example:

    function Test(a,b,c)
    {
    }


 //callling Test
  Test(1)
  Test(1,2)  // now inside Function Test c will be undefined
  Test(1,2,3)
  Test(1,2,3,4) // note here i have passed an additonal paramter that will be totally ignored

You can create a calculator like below

function Calculate(num1, num2, operation)
{
operation= operation || 'sum'; //sum is the default operator
if(operation == 'sum')
{
return num1 + num2 ;
}
if(operation == 'multiply')
{
return num1 * num2 ;
}
if(operation == 'subtract')
{
return num1 - num2 ;
}
if(operation == 'divide')
{
return num1 / num2 ;
}
}


Calculate(1, 2)  //returns 3  -- defaut operator is picked
Calculate(1, 2, 'sum')  //returns 3
Calculate(1, 2, 'multiply')  //returns 2


Just define the function to take three arguments.

function myFunction (foo, bar, baz) {
    if (typeof baz !== "undefined") {

    } else {

    }
}


Javascript functions can take as many or as little parameters as you like.

Say you have a function:

function fn (a, b, c) {}

But you only give it two parameters, the last will be undefined. If you give it more parameters than you have declared, you can access it with the arguments object:

arguments[3] will give you the fourth parameter. Arguments is basically an Array without any Array functions. It just has a length property and values indexed by order (e.g. 0, 1, 2, 3...).

The way to use this is:

function fn (a, b, c) {
    alert(arguments[3]);
}
fn(0, 0, 0, 3);

This will alert 3.

EDIT:

This isn't exactly related, but functions are the same as any other object. For example, you can take a function (fn from the previous example), and assign properties to it.

function fn (a) {alert(a);}
fn.something = 'Hello!!';

Then you can do this:

fn(fn.something);

This would alert 'Hello!!'. Cool, huh?


Use :

function itsme(arg1, arg2, arg3){
    arg1 = arg1|| false;
    arg2 = arg2|| false;
    arg3 = arg3|| false;
    ...
}

or

function itsme(){
    arg1 = arguments[0]||false;
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜