just starting out with JavaScript and jQuery, and i have this problem:
foo(validation);
function foo(func) {
var time = new Date().getTime();
// do some other s开发者_如何学Gotuff
func("foobar" + time);
}
function validation(elementName) {
// do stuff
}
but when i call function foo with the validation function pointer, i would also like to pass in the string "foobar" at that point.
What about:
function foo(str, func) {
var time = new Date().getTime();
// do some other stuff
func(str + time);
}
function validation(elementName) {
// do stuff
}
foo("foobar", validation);
You can just invoke another (anonym) function:
foo(function() {
validation('foobar');
});
By the way, there are no real "pointers" in ECMAscript, it's a reference tho. I guess you're doing it this way for educational reasons (passing a funarg = functional argument
) into a high-order function, but you can simplify the whole thing into:
validation('foobar' + (+new Date()));
ah i see... you shouldn't use this may one say but try:
eval("func(\"foobar"+time+"\")");
Since JavaScript is that flexible, here's another way using currying.
function createFoo(string) {
return function(aFunction) {
var time = new Date().getTime();
// ..
aFunction(string + time);
};
}
var foobar = createFoo("foobar");
foobar(validation);
what about if you send as foo parameters the function name and an array of arguments for that function?
function foo(func,funcArgs){
func.apply({},[new Date().getTime()].concat(funcArgs));
}
function validate(arguments){
}
//then you could pass anything to the validate "pointer"
foo(validate,[argument1,argument2,/*...*/argumentn]);
精彩评论