gpt4 book ai didi

javascript - 如何从传递给在实例上调用的 "bind"方法的预定义函数中访问对象实例的上下文?

转载 作者:行者123 更新时间:2023-11-30 15:56:10 25 4
gpt4 key购买 nike

我有这个片段:

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

第一个 console.log 输出:

[img]
0: img // expandable
length: 1
__proto__: Object[0] // expandable

第二个 console.log 输出:

<img src=​"/​images/​Tree.jpg">​

为什么两个输出不同?

另外,我需要在别处定义传递给 test_img.bind 的函数。即,

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

如何才能使 new_this 与原始代码段中的 this 相同?

最佳答案

作为第一个问题的答案,区别在于第一个输出的构造函数是 jQuery.fn.init,而第二个输出的构造函数是 HTMLImageElement。您可以使用 test_img[0] 从第一个输出访问图像。
如果您想使用一些预定义的函数,只需将 new_this 替换为 this

关于javascript - 如何从传递给在实例上调用的 "bind"方法的预定义函数中访问对象实例的上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38493672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com