简体   繁体   中英

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?

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);

You will have to call:

var some_control = {id: "myOwnId"};
doStuff(some_control);

It creates an object using object literals, { } . Then, a property id is defined. This whole object is passed as a parameter to function doStuff .

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.

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

doStuff({id: "yourID"}); // works now

Test it on jsFiddle .

There's one problem left: You don't have access to the inner value parameter but I assume that you're going to bind this anonymous function to an event listener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM