javascript – 如何在JQuery回调函数中获取对象引用?

假设我们有一个名为aObject的
javascript对象,test()函数在
JQuery中用作回调函数

var aObject = {
    aVariable : 'whatever value',
    test : function() {
        // Trying to access property. But doesn't work as expected since I am getting the DOM element, not the aObject reference
        var temp = this.aVariable;
    }
}

var anInstanceOfAObject = $.extend({}, aObject);

anInstanceOfAObject.someFunction = function () {
    // I have to put "this" in a variable since "this" in the context below refers to the DOM element, not the instance of the object
    var placeHolder = this;
    $('some random div.element').theJavascriptFunction({
        "theJavascriptCallbackFunction": placeHolder.test,
    });
}

在test()函数中,通常“this”的上下文是DOM元素.我的问题是如何引用aObject,因为我们不能使用“this”来引用它.

编辑:我不确定上面的语法是否是实例化对象的正确/首选方法.我看到一些使用这种语法的例子

var aObject = function() {....

如果这似乎与问题有关,请通知我.

最佳答案 你只需要包装你的方法调用来获得正确的:

anInstanceOfAObject.someFunction = function () {
    var placeHolder = this;
    $('some random div.element').theJavascriptFunction({
        "theJavascriptCallbackFunction": function() { placeHolder.test() }
    });
}

当你只使用placeHolder.test作为回调时,你只是将一个引用移交给测试函数,并且将使用DOM元素调用该函数.

你也可以尝试bind

anInstanceOfAObject.someFunction = function () {
    var placeHolder = this;
    $('some random div.element').theJavascriptFunction({
        "theJavascriptCallbackFunction": this.test.bind(this)
    });
}
点赞