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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With