Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign function to variable and pass parameter

I guess this is probably an easy problem, but I cannot figure it out myself (using the wrong search criteria?).

As the title says, I want to assign a function to a variable and pass a variable to that function like this:

function doStuff(control) {
    var myObj = {
        "smooth": false,
        "mouseup": function(value) {
            jQuery(_getSelectorStringFromControlId(control.id)).blur();
        }
    };
}

Now I want the control.id to be replaced with its actual value before the function is assigned to the mouseup variable.

So when control.id = 'myOwnId' then myObj.mouseup should be:

function(value) {
    jQuery(_getSelectorStringFromControlId('myOwnId')).blur();
}

How can this be accomplished?

like image 438
Moolie Avatar asked Aug 30 '25 18:08

Moolie


2 Answers

this is the basic form for assigning a function to a variable

var myFunc = function(x) {
   console.log(x);
}

once that is done, you can invoke the function like so (passing in anything you want)

myFunc(1);
like image 149
hvgotcodes Avatar answered Sep 02 '25 08:09

hvgotcodes


I think what you're looking for here is a closure, which is where a function which remembers variables that were in scope when it was created ("control" in your case) but then gets called from elsewhere. In your example, you can return myObj from the doStuff function, and whenever you call mouseup() it will refer to the "right" value of control. So in fact, you're creating a closure in that example code already.

If you want to make the closure keep a reference to just the id, you could do this:

function doStuff(control) {
    var myId = control.id;
    var myObj = {
        "smooth": false,
        "mouseup": function(value) {
            jQuery(_getSelectorStringFromControlId(myId)).blur();
        }
    };
}

You can now have lots of copies of myObj floating round your page, and on each one, mouseup() will be using a different id.

More info on closures: https://developer.mozilla.org/en/JavaScript/Guide/Closures

As an aside, closures are the best thing ever for utterly astonishing people who've never done any functional programming.

like image 33
N3dst4 Avatar answered Sep 02 '25 08:09

N3dst4