如何在JQuery回调函数中获取对象引用? [英] How to get the object reference inside a JQuery callback function?

查看:110
本文介绍了如何在JQuery回调函数中获取对象引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say that we have a javascript object called aObject and the test() function is used as a callback function in 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来引用它。

Inside that test() function, normally the context of "this" is the DOM element. My question is how to reference aObject since we can't use "this" to reference it.

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

I am not sure if the syntax above is the correct/preferred way to instantiate an Object. I see some examples using this syntax

var aObject = function() {....

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

Please inform me if this seems to be relevant to the problem.

推荐答案

你只需要打包方法调用就可以获得正确的这个

You just need to wrap your method call to get the right this:

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

当你只使用 placeHolder.test 作为回调,您只是将对 test 函数的引用移交给该函数,并且该函数将使用DOM元素调用为这个

When you use just placeHolder.test as the callback, you're just handing over a reference to the test function and that function will be called with the DOM element as this.

您也可以尝试 bind

You could also try bind:

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

这篇关于如何在JQuery回调函数中获取对象引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆