Captastic
Captastic

Reputation: 1066

assign a copy of a function to a var

Is it possible to define a function and then assign copies of the function to different vars?

This is essentially how far I've got...

function add(x, y){
   return x + y;
}

var function1 = new add()
var function2 = new add()

This doesn't seem to work as it's trying to run the add function each time. The same goes for

var function1 = new function add()

Do I need to be using prototype in some way or am I looking at it in the wrong way?

Upvotes: 0

Views: 105

Answers (4)

6502
6502

Reputation: 114559

A function in Javascript is an object as any other.

You can create many references to the same function and store them for example in an array

function add(x, y) {
    return x + y;
}

var v = [add, add, add, add];

alert(v[3](33, 9)); // Will show 42

The only "magic" thing happens when you call a function getting it from an object member lookup

x = {};
x.f = add;
x.f(12, 3);  // Returns 15

the "strange" thing that will happen is that this inside the function when called that way will be the object, and not the global window object as it happens when you call a function directly.

This also means that, confusingly enough,

x.f(z);

is not the same as

[x.f][0](z);

or as

var ff = x.f;
ff(z);

because in the first case this will be x, in the second case this will be the array instead and in the third case it will be the global window object.

Upvotes: 0

jhnlsn
jhnlsn

Reputation: 186

if your just trying to create references to the function just make this modification

function add(x, y){
  return x + y;
}

var function1 = add;
var function2 = add;

After which you are able to call the functions like this.

function1(10,11);

function2(1,2);

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68440

This should do the trick

var function1 = add;
var function2 = add;

Upvotes: 5

Femaref
Femaref

Reputation: 61467

You are evaluating the function. To assign the function itself to a variable, use

var function1 = add;
var function2 = add;

However, it's not quite clear why you want to copy the function.

Upvotes: 3

Related Questions