如何在jQuery中使用javascript调用方法?
是否可以使用javascript的call方法
(如[mdn文档]中所述) 为了传递参数 this
?
例如,有这样的代码:
console.log(this);
$('#image_id').load(function () {
console.log(this);
});
我希望第二个 this
(包含在 load 函数
中的那个)与第一个相同。
我尝试过
console.log(this);
$('#image_id').load.call(this, function () {
console.log(this);
});
但它不起作用。
预先感谢大家的任何建议。
Is it possible to use the call method
of javascript (as described in the [mdn documentation])
in order to pass the argument this
?
Having for example this code:
console.log(this);
$('#image_id').load(function () {
console.log(this);
});
I want that the second this
(the one included in the load function
) refers to the same as the first one.
I've tried with
console.log(this);
$('#image_id').load.call(this, function () {
console.log(this);
});
But it doesn't work.
Thank you all in advance for any suggestion.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不需要
call
(或apply
),您应该这样做:
Javascript 具有词法作用域,这意味着变量
that
可用到您的回调,并具有其定义位置的值。在本例中,that
被定义为外部作用域中的this
。You don't need
call
(orapply
)You should do this instead:
Javascript has lexical scoping, which means that the variable
that
is available to your callback, and has the value of where it is defined. In this case,that
is defined to bethis
in the outer scope.不是那样的,因为你没有调用回调。这是内部调用的。
不过,您可以使用
.bind
。但它在旧版浏览器中不可用。 (这是本机
.bind()
,不是 jQuery 的。)jQuery 有一个可以工作的东西,称为
$.proxy
......其中第一个参数是您的函数,第二个参数是您要在回调中用于
this
的值。Not like that, because you're not calling the callback. It's being called internally.
You could use
.bind
though.But it isn't available in older browsers. (This is native
.bind()
, not jQuery's.)jQuery has something that will work called
$.proxy
......where the first argument is your function, and the second argument is the value you want to use for
this
in the callback.是的,您可以使用任何
.call
jQuery 函数,但这只会影响该函数。您传递的函数是一个单独的回调函数,其中this
由 jQuery 控制。您可以使用
$.proxy
强制回调上下文。如果你想做的不仅仅是记录,它会变得更难看:
Yes you can
.call
jQuerys function with whatever, but that only affects that function. The function you pass is a separate callback function withthis
controlled by jQuery.You can use
$.proxy
to force a context of the callback.If you wish to do more than logging it becomes more ugly: