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

How can I access an object instance's context from within a predefined function passed to the "bind" method invoked on the instance?

我有这个片段:

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.

看这个例子:

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);
  1. 要使new_this与此相同:您需要将其更改为事件响应函数中的Jquery对象。

  2. 在别处定义传递给事件的函数:将函数作为参数传递给事件响应函数。

  3. 使用 .on 替换 .bind,因为 .bind 可能随时从未来版本中删除。没有理由继续使用 .bind,而是有充分的理由更喜欢 .on。