如何将此上下文传递给函数? [英] How do I pass the this context to a function?

查看:169
本文介绍了如何将此上下文传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这将是我可以轻松谷歌的东西,但也许我不是在问正确的问题......

I thought this would be something I could easily google, but maybe I'm not asking the right question...

我该怎么设置这个在给定的javascript函数中引用?

How do I set whatever "this" refers to in a given javascript function?

例如,与大多数jQuery的函数一样,例如:

for example, like with most of jQuery's functions such as:

$(selector).each(function() {
   //$(this) gives me access to whatever selector we're on
});

如何调用/调用我自己的独立函数,这些函数在调用时具有适当的this引用?我使用jQuery,所以如果有一个特定于jQuery的方法,这是理想的。

How do I write/call my own standalone functions that have an appropriate "this" reference when called? I use jQuery, so if there's a jQuery-specific way of doing it, that'd be ideal.

推荐答案

Javascripts .call() .apply()方法允许您为函数设置上下文

Javascripts .call() and .apply() methods allow you to set the context for a function.

var myfunc = function(){
    alert(this.name);
};

var obj_a = {
    name:  "FOO"
};

var obj_b = {
    name:  "BAR!!"
};

现在你可以致电:

myfunc.call(obj_a);

哪会提醒 FOO 。反过来,传递 obj_b 会提醒 BAR !! .call() .apply()之间的区别是 .call() 如果要将参数传递给函数并且 .apply()需要一个数组,则采用以逗号分隔的列表。

Which would alert FOO. The other way around, passing obj_b would alert BAR!!. The difference between .call() and .apply() is that .call() takes a comma separated list if you're passing arguments to your function and .apply() needs an array.

myfunc.call(obj_a, 1, 2, 3);
myfunc.apply(obj_a, [1, 2, 3]);

因此,您可以轻松编写函数 hook 使用 apply()方法。例如,我们想要为jQuerys .css()方法添加一个功能。我们可以存储原始函数引用,用自定义代码覆盖函数并调用存储函数。

Therefore, you can easily write a function hook by using the apply() method. For instance, we want to add a feature to jQuerys .css() method. We can store the original function reference, overwrite the function with custom code and call the stored function.

var _css = $.fn.css;
$.fn.css = function(){
   alert('hooked!');
   _css.apply(this, arguments);
};

因为神奇的参数对象是一个数组像对象一样,我们可以将它传递给 apply()。这样我们保证所有参数都传递给原始函数。

Since the magic arguments object is an array like object, we can just pass it to apply(). That way we guarantee, that all parameters are passed through to the original function.

这篇关于如何将此上下文传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆