最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - JavaScript function pointer problem - Stack Overflow

programmeradmin0浏览0评论

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 stuff
  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.

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 stuff
  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.

Share Improve this question asked Jan 20, 2011 at 8:47 pingupingu 8,82712 gold badges52 silver badges88 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

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

发布评论

评论列表(0)

  1. 暂无评论