我认为这是我可以很容易地搜索到的东西,但也许我没有问对问题……
如何在给定的javascript函数中设置"this“所指的内容?
例如,就像jQuery的大多数函数一样:
$(selector).each(function() {
//$(this) gives me access to whatever selector we're on
});
如何编写/调用我自己的独立函数,这些函数在被调用时具有适当的"this“引用?我使用的是jQuery,所以如果有一种特定于jQuery的方法,那将是最理想的。
发布于 2010-09-03 02:37:03
var f = function () { console.log(this); }
f.call(that, arg1, arg2, etc);
其中,that
是您希望函数中的this
成为的对象。
发布于 2019-03-19 18:44:41
另一个基本示例:
不工作:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
};
img.src = reader.result;
工作中:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
}.bind(this);
img.src = reader.result;
所以基本上:只需将.bind(这)添加到您的函数
发布于 2017-06-16 02:11:25
您可以使用bind函数在函数中设置this
的上下文。
function myFunc() {
console.log(this.str)
}
const myContext = {str: "my context"}
const boundFunc = myFunc.bind(myContext);
boundFunc(); // "my context"
https://stackoverflow.com/questions/3630054
复制相似问题