简体   繁体   中英

“This” in JS Object Literal - Different meaning in event Callback

How can I refer the the object itself in an event callback defined within an object literal in JS/jQuery please?

I have researched various answers and articles, such as this question: How to access the correct `this` inside a callback? but only found myself more confused.

It makes sense that this should refer to the element that was clicked as we need access to it, but how then do I refer the the object containing the binding function itself?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>This</title>
    <script
    src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>
</head>
<body>

    <button id="test">Click Me</button>
    <script>

        $( document ).ready( function() {

            console.log(MyObj.introspect());
            MyObj.bindEvents();

        } );

        MyObj = {
            myProperty : 'a property',

            bindEvents : function(){
                $('#test').on('click', MyObj.introspect)
            },

            introspect : function(){
                console.log(this);
            }
        }
    </script>
</body>
</html>

In your case, you'd use MyObj , just like you did in bindEvents , since it's a singleton:

MyObj = {
    myProperty : 'a property',

    bindEvents : function(){
        $('#test').on('click', MyObj.introspect)
    },

    introspect : function(){
        console.log(MyObj);
        // ---------^^^^^
    }
}

Side note: Your code is falling prey to what I call The Horror of Implicit Globals . Be sure to declare your variables (with var , or ES2015's let or const ). In your case, you can make MyObj entirely private since you only need it in your own code, by moving it into the ready callback and declaring it:

$( document ).ready( function() {
    var MyObj = {                                    // Note the `var`
        myProperty : 'a property',

        bindEvents : function(){
            $('#test').on('click', MyObj.introspect)
        },

        introspect : function(){
            console.log(MyObj);
        }
    };                                               // Also added missing ; here

    console.log(MyObj.introspect());
    MyObj.bindEvents();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM