繁体   English   中英

javascript传递函数作为参数

[英]javascript passing function as parameter

如果我有这个:

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

我可以把它重写为

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

但是,如果我需要传递这样的参数怎么办:

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

还有其他选择吗?

谢谢。

作为@Jashwant说,同样this将在功能中使用,无论如何,所以它你不必担心(在你的例子)的一个值。

请注意,如果需要,可以按照自己的描述进行操作,静态值很容易,并称为currying 一个javascript示例是: http//www.dustindiaz.com/javascript-curry/

您应该修改SomeFunction的实现,以使它们在没有参数的情况下工作。

例如,如果您有:

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

你可以这样写:

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

在对所有三个回调执行此操作后,您可以使用第二个代码示例来绑定它们。

的意思this一个javascript函数内部不依赖于词法范围的功能被定义-例如,下面的提示“你好,世界!”,如果事件this.name没有定义时, greet创建

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

以下也警告“Hello,World!”:

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

在幕后,发生的事情类似于:

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

因此,您可以安全地混合#2和#3片段。

BTW:

大多数jQuery事件处理程序都是通过引用jQuery事件对象作为第一个参数来调用的,所以如果你发现this工作方式很棘手(或者如果你担心你必须向每个同事解释),你也可以使用event.delegateTarget而不是this

参见例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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