0

I want to write a common confirm method like

var confirmDelete = function (fun) {
    if (confirm("Do you want to delete " + arguments[1])) {
        $(arguments[2]).remove();
        fun(arguments[3]);
    }
    return false;
}

It's working fine for fun with one parameter, but I want to suit for two or more parameters, how I can do it?

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
atu0830
  • 405
  • 7
  • 15

3 Answers3

0

every javascript Function object has a method named apply. apply will call your function using the given context and the given arguments.

var confirmDelete=function(fun) {
    if(confirm("Do you want to delete "+ arguments[1])) {
        // remove the first two elements in arguments, and use the resulting array as a new set of
        // arguments to fun
        fun.apply(this, Array.slice(arguments, 2));
    }
}
Dan O
  • 6,022
  • 2
  • 32
  • 50
0

In JavaScript you can pass as many parameters as you want.

If you don't pass them, they will be undefined.

So... You can do something like this:

var confirmDelete = function(arg1, arg2, arg3) {
    if (typeof arg2 === 'undefined') {
        arg2 = "default value for arg2";
    }
    if (typeof arg3 === 'undefined') {
        arg3 = "default value for arg3";
    }
    // do more stuff...
}

You can also read about the magical arguments variable here.

Community
  • 1
  • 1
jahroy
  • 22,322
  • 9
  • 59
  • 108
0

You can rewrite your function something like

var confirmDelete = function fun(arg1, arg2) {
  // number of parameter as your need
  // TODO some stuff
  fun(arg1 -1, arg2 +3); // call it recursively 
  return false; 
}
simpletron
  • 739
  • 4
  • 14