开发者

"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 开发者_如何学Go= 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜