Javascript 如何将 this 上下文传递给函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3630054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:29:54  来源:igfitidea点击:

How do I pass the this context to a function?

javascriptjqueryscopethis

提问by user126715

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

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

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

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

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

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

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

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.

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

回答by jAndy

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

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

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

var obj_a = {
    name:  "FOO"
};

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

Now you can call:

现在你可以调用:

myfunc.call(obj_a);

Which would alert FOO. The other way around, passing obj_bwould 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.

哪个会提醒FOO。反之,路过obj_b就会警觉BAR!!.call()和之间的区别在于,如果您将参数传递给函数并需要一个数组,.apply()则它.call()采用逗号分隔的列表.apply()

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

Therefore, you can easily write a function hookby 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.

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

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

Since the magic argumentsobject 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.

由于魔法arguments对象是一个类似对象的数组,我们可以将它传递给apply(). 这样我们保证,所有参数都传递给原始函数。

回答by palswim

Use function.call:

使用function.call

var f = function () { console.log(this); }
f.call(that, arg1, arg2, etc);

Where thatis the object which you want thisin the function to be.

that您希望this函数中的对象在哪里。

回答by Mic

jQuery uses a .call(...)method to assign the current node to thisinside the function you pass as the parameter.

jQuery 使用一种.call(...)方法将当前节点分配到this您作为参数传递的函数内部。

EDIT:

编辑:

Don't be afraid to look inside jQuery's code when you have a doubt, it's all in clear and well documented Javascript.

当您有疑问时,不要害怕查看 jQuery 的代码,所有内容都在清晰且有据可查的 Javascript 中。

ie: the answer to this question is around line 574,
callback.call( object[ name ], name, object[ name ] ) === false

即:这个问题的答案在第 574 行左右,
callback.call( object[ name ], name, object[ name ] ) === false

回答by Joery

Another basic example:

另一个基本示例:

NOT working:

不工作:

var img = new Image;
img.onload = function() {
   this.myGlobalFunction(img);
};
img.src = reader.result;

Working:

在职的:

var img = new Image;
img.onload = function() {
   this.myGlobalFunction(img);
}.bind(this);
img.src = reader.result;

So basically: just add .bind(this) to your function

所以基本上:只需将 .bind(this) 添加到您的函数中

回答by Scott Jungwirth

You can use the bindfunction to set the context of thiswithin a function.

您可以使用绑定函数来设置this函数内的上下文。

function myFunc() {
  console.log(this.str)
}
const myContext = {str: "my context"}
const boundFunc = myFunc.bind(myContext);
boundFunc(); // "my context"