将默认全局对象作为“ this”传递给外部javascript模块

时间:2018-10-20 22:39:49

标签: javascript this

我想知道如何将“ this”传递给外部模块(script.js)。 当前传递给'script.js'的'this'是不确定的,但是我想找到一种传递默认全局对象的方法。顺便说一句,script.js是由另一个库自动生成的,因此我无法进行任何更改。请帮忙。

index.html

<script src='./script.js' defer></script>
<script>
    var interval = setInterval(function () {
        if (document.readyState === 'complete') {
            clearInterval(interval);

            (function (scope) {
                console.log('this inside of function')
                console.log(scope) //this prints 'global {frames: global, ..}
            })(this)  // <<<<< THIS works
        }
    }, 100);
</script>

script.js

(function (scope) {
    console.log('this inside of script.js')
    console.log(scope)    /// this prints 'undefined'
})(this)   // << THIS is undefined.

0 个答案:

没有答案