为什么在闭包中比window.parent更好地引用window.parent?

时间:2015-06-26 04:20:23

标签: javascript closures subdomain

outer.html托管于www.blah.com

<html>

<head>
    <script>
    (function(){
        var doc,where,iframe = document.createElement('iframe');
        where = document.getElementsByTagName('script')[0];
        where.parentNode.insertBefore(iframe, where);

        doc = iframe.contentWindow.document;
        doc.open()._l = function() {
                var js = this.createElement("script");
                js.src = "inner.js";
                this.body.appendChild(js);
        };

        doc.write('<body onload="document._l();">');
        doc.close();
    })();

    setTimeout(function(){
        console.log("outer: was " + document.domain);
        document.domain = "blah.com";
        console.log("outer: is " + document.domain);
    }, 500);
    </script>
</head>

<body>
</body>
</html>

inner.js如下:

(function(w){
    w = window.parent;
    function test() {
        try {
            console.log("try:" + window.parent.document.domain);
        }
        catch (e){
            console.log("catch:" + w.document.domain);
        }
    }

    test();
    //document.domain of hosting page (parent) changes in between these calls
    setTimeout(test, 1000);
})(window);

请注意,在调用test()之间,托管窗口中的document.domain更改为blah.com

当然,对test()的第一次打印打印: try:www.blah.com

第二次调用test()是问题所在。

在Chrome中,我看到: try:blah.com,这是有道理的。

在IE11&amp; IE10,我明白了: catch:blah.com

所以,window.parent.document.domain失败,但w.document.domain工作,即使window.parent === w

为什么?

0 个答案:

没有答案