Redefining a function in JScript


Taking a leaf out of Eric‘s book, I’m going to re-post a question I received in mail here. The question was (essentially):




How do you re-define a function in JScript, and keep the parameters intact?

Simple!

There are (at least) two ways to do it:

1) Just re-define the function using an expression:




  
// First definition




  
function
foo(x) { print(x) }


  foo(42)

// prints 42






  

// Second definition




  foo =
function
(x) { print(x * 2) }


  foo(42)

// prints 84




2) Use Function constructor with more than one parameter:




  
// First definition




  
function
foo(x) { print(x) }


  foo(42)

// prints 42






  

// Second definition




  foo =
new
Function(“x”, “print(x * 2)”)


  foo(42)

// prints 84




Note that you can’t do it like this, because the second declaration will clobber the first before your program ever starts to execute:




  
// First definition (clobbered)




  
function
foo(x) { print(x) }


  foo(42)

// prints 84!






  

// Second definition (clobbers first)




  
function foo
(x) { print(x * 2) }


  foo(42)

// prints 84




The Function constructor takes the first n-1 parameters and concatenates them with commas, then uses them for the argument list. The nth parameter is the function body. This is kind of cool (in a whacky way) because if you had 3 arguments, you could say:




  
// Three explicit parameters holding the three


  // arguments





  foo =
new
Function(“x”, “y”, “z”, “print(x + y + z)”)




or




  
// One explicit parameter containing three


  // arguments





  foo =
new
Function(“x, y, z”, “print(x + y + z)”)




or




  // One explicit parameter containing two arguments,


  // and a second parameter containing the third argument





  foo =
new
Function(“x, y”, “z”, “print(x + y + z)”)




You can learn more the Function constructor on MSDN.

Comments (2)

  1. Raman says:

    is this ECMA compatible?