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

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

问题描述

我认为这会是我可以轻松使用谷歌搜索的东西,但也许我没有问正确的问题......

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

如何在给定的 javascript 函数中设置this"所指的任何内容?

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

因此,您可以使用 apply() 方法轻松编写函数 hook.例如,我们想向 jQuery 的 .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);
};

由于神奇的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.

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

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