ammcom
ammcom

Reputation: 1034

Javascript - keep reference to function before changing it

My code looks like this:

function x(a,b)
{
     return a + b;
}

var f = x;

function x(a,b)
{
     return a - b;
}

var res = f(2,1);

I expect that the result is 3 as f is pointing to function x before modifying it, but it isn't the case, how can I keep a reference to a function that is foing to be redefined?

Upvotes: 1

Views: 153

Answers (3)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

Functions and variable declarations (but not variable assignments) are "hoisted" to the top of their containing scope.

So your code is equivalent to this:

function x(a,b) {
  return a + b;
}

function x(a,b) {  //this overwrites the previous function declaration
  return a - b;
}

var f;
var res;

f = x;

res = f(2,1);  //1

It should now be clear why f(2,1) is 1 instead of 2.

You can overcome this by creating functions as variables instead:

var x = function(a, b) {
  return a + b;
}

var f = x;
console.log(f(2, 1));  //3

var x = function(a, b) {
  return a - b;
}

var f = x;
console.log(f(2, 1));  //1

Upvotes: 3

slebetman
slebetman

Reputation: 113876

Function declarations are processed before expressions. Therefore, from the point of view of the interpreter, your code is interpreted as this:

function x(a,b)
{
     return a + b;
}

function x(a,b)
{
     return a - b;
}

var f = x;

var res = f(2,1);

The solution is to re-assign the function using a function expression instead of a function declaration. This is because as I mentioned above expressions are processed after declarations:

function x(a,b)
{
     return a + b;
}

var f = x;

x = function (a,b) // <--------- this fixes your problem
{
     return a - b;
}

var res = f(2,1);

Note, that since declarations are processed before expressions, the following would work as well:

var f = x;

x = function (a,b)
{
     return a - b;
}

var res = f(2,1);

function x(a,b) // this is processed first
{
     return a + b;
}

Upvotes: 4

Wes Foster
Wes Foster

Reputation: 8900

Assign your functions to variables when creating them:

var f1 = function(a, b) {
  return a + b;
}

var f2 = f1;

f1 = function(a, b) {
  return a - b;
}

alert( f1(2,1) );  // < Will subtract
alert( f2(2,1) );  // < Will add

This allows you to easily clone the function.

Upvotes: 2

Related Questions