[英]How can I access an object instance's context from within a predefined function passed to the “bind” method invoked on the instance?
I have this snippet: 我有这个片段:
var test_img = $("<img />");
test_img.attr("src", img_url);
test_img.unbind("load");
console.log(test_img);
test_img.bind("load", function ()
{
console.log(this);
});
The first console.log
outputs: 第一个
console.log
输出:
[img]
0: img // expandable
length: 1
__proto__: Object[0] // expandable
The second console.log
outputs: 第二个
console.log
输出:
<img src="/images/Tree.jpg">
Why are the two outputs different? 为什么两个输出不同?
Also, I need to define the function that gets passed to test_img.bind
elsewhere. 另外,我需要定义在其他地方传递给
test_img.bind
的函数。 Ie, 也就是说,
function predefined_function()
{
console.log(new_this);
}
var test_img = $("<img />");
test_img.attr("src", img_url);
test_img.unbind("load");
console.log(test_img);
test_img.bind("load", predefined_function);
How can I make it so that new_this
is the same as this
in the original snippet? 我怎样才能让这个
new_this
相同this
在原来的片段?
As an answer to your first question, the difference is because the constructor of the first output is jQuery.fn.init
, but the constructor of the second output is HTMLImageElement
. 作为第一个问题的答案,不同之处在于,第一个输出的构造函数是
jQuery.fn.init
,而第二个输出的构造函数是HTMLImageElement
。 You can access image from first output using test_img[0]
. 您可以使用
test_img[0]
从第一个输出访问图像。
If you want to use some predefined function, just replace new_this
with this
. 如果要使用一些预定义的函数,只需将
new_this
替换为this
。
See this example: 请参阅以下示例:
https://jsfiddle.net/y89zk2k8/1/ https://jsfiddle.net/y89zk2k8/1/
var textDiv = $("<div />").append("click me :)"),
func = function() {
var $me = $(this);
console.log($me);
};
textDiv.off("click");
console.log(textDiv);
textDiv.on("click", func);
$("body").append(textDiv);
To make new_this same as this: You need to change it to the Jquery Oject in the event response function. 要使new_this与此相同:您需要在事件响应函数中将其更改为Jquery Oject。
Define the function that gets passed to the event elsewhere: Pass the function as param to the event response function. 在其他地方定义传递给事件的函数:将函数作为参数传递给事件响应函数。
Use .on to replace .bind, because .bind may be removed from future versions at any time. 使用.on替换.bind,因为.bind可能会随时从将来的版本中删除。 There is no reason to keep using .bind and every reason to prefer .on instead.
没有理由继续使用.bind,也没有理由更倾向于使用.on。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.