Jem
Jem

Reputation: 6426

Function in a variable, passing a parameter

I can't seem to get back on track with this one. I simply put a function in a variable and want to call it later, providing it with a parameter:

var logic = function(itemId) {               
    console.log(itemId);
};

jQuery("#flipright").click(function() {  logic.apply(1); } );

This prints "undefinded".

What am I missing?

Upvotes: 0

Views: 118

Answers (2)

gion_13
gion_13

Reputation: 41533

Simply call logic(1).
If you want to pass a context, you can use call or apply :

logic.apply(context, [1]);
// or
logic.call(context, 1);

You should use apply or call if you want to pass a context to another function - meaning that the this keyword in the called function will refer to whatever context you are passing to it.
Here's a scenario :

var logic = function(itemId) {               
    console.log(this,itemId);
};

jQuery("#flipright").click(function() {  
    // output to console the current jquery object and "1"
    logic.call(this,1);
});

Upvotes: 4

Yoshi
Yoshi

Reputation: 54659

Make it:

jQuery("#flipright").click(function() {  logic(1); } );

ref for apply: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply

Upvotes: 1

Related Questions