简体   繁体   中英

“this” in OOP events

Look this code:

<script type = "text/javascript">
    function mouseClick (container) {
        container.appendChild (document.createTextNode ("Can you show me ? Try clicking anywhere."));

        this.tryShowMe = "Yes man ! You can !"

        window.addEventListener ("click", function (event) {
            var ok = typeof this.tryShowMe === "undefined" ? "No, you can't." : this.tryShowMe;

            alert (ok);
        }, false);
    }

    window.addEventListener ("load", function () {
        new mouseClick (document.body);
    }, false);
</script>

The "this.tryShowMe" refers to the element "window", instead, I want to refer to the object. Can I do that ?

Thanks

That's a common pitfall in JavaScript.

You're adding the event listener to window therefore window is calling the function, which will result in the this inside of the function being set to window .

this never references an outer scope in JavaScript, even if you call a plain function like foo() inside another function, the this inside of foo will default to the global object.

If you want to access an outer this you need to keep a reference to it:

someObject.method = function() {
    var that = this;
    function test() {
        that; // refers to someObject
        this; // refers to window
    }
    test();
}

For an overview on the possible values and pitfalls of this , take a look here .

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