简体   繁体   中英

javascript passing function as parameter

If I have this:

$(SomeID).on({
    click: function () { SomeFunction1(); },
    mouseenter: function () { SomeFunction2(); },
    mouseleave:function () { SomeFunction3(); }
}, '.SomeClass');

I can rewrite it as

$(SomeID).on({
    click: SomeFunction1,
    mouseenter: SomeFunction2,
    mouseleave: SomeFunction3
}, '.SomeClass');

But what if I need to pass some parameter like this:

$(SomeID).on({
    click: function () { SomeFunction1($(this)); },
    mouseenter: function () { SomeFunction2($(this).index()); },
    mouseleave: function () { SomeFunction3($(this).index()); }
}, '.SomeClass');

Is there an alternative?

Thanks.

As @Jashwant says, the same this would be used in the function anyway, so it's the one value you don't need to worry about (in your example).

Note that you could do as you describe if you needed to, it's easy for static values, and is called currying . A javascript example would be: http://www.dustindiaz.com/javascript-curry/

You should modify implementation of SomeFunction s to get them work without parameter.

For example, if you have:

function SomeFunction2(arg) {
  //do something assuming arg to be $(this).index()
}

You can write it like that:

function SomeFunction2() {
  var arg = $(this).index();
  //do exactly the same
}

After doing that for all three callbacks, you can use your second code sample to bind them.

The meaning of this inside a javascript function does not depend on the lexical scope the function was defined in – for example, the following alerts "Hello, World!", event if this.name is not defined when greet is created

var x = { name: 'World' };
var greet = function() { alert('Hello, ' + this.name); };
x.greet = greet;
x.greet();

the following too alerts "Hello, World!":

var x = { name: 'World' };
var y = { name: 'Dude', greet: function() { alert('Hello, ' + this.name); } };
x.greet = y.greet;
x.greet();

Behind the scenes, what goes on is similar to:

var greet = function() { alert('Hello, ' + this.name); };
greet.call({ name: 'World' });

So you can safely mix your #2 and #3 snippets.

BTW:

most jQuery event handlers get called with a reference to the jQuery event object as the first parameter, so if you find how this works tricky (or if you fear you'll have to explain to each one of you colleagues), you can also use event.delegateTarget instead of this .

See for example:

$(document).click(function(evt){ alert (evt.delegateTarget === this); });

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