简体   繁体   中英

Javascript ES6 reference a variable in the global scope but not in the window scope

I am upgrading my code from ES5 to ES6. In ES5 I dynamically load the function by creating a new script which then loads the file asynchronously. the code is as follows:

loadClass : function(className) {
    if(typeof window[className] !== "function") {
        page.getCode(className, dirName);
        return;
    } ...


getCode(className) {
    var fileName = className.toLowerCase();
    var newScript = document.createElement('script');
    newScript.setAttribute("type", "text/javascript");
    newScript.setAttribute("src", '/public/js/' + fileName + '.js');
    var parmArr = [className];
    newScript.addEventListener('load', this.loadClass.bind("", parmArr));
    document.getElementsByTagName("head")[0].appendChild(newScript);
    return;
}

In ES5 the function is loaded in the global scope which in this case is window. I have the function/class name in a string and I can reference the class using window[classname] as shown in the code above. In ES6 I changed the calling and called functions to a class. Now when it loads the script it exists as Myclass function() in the global scope but not in the window scope as shown in the Chrome debugger like so:

Myclass ()
[[Scopes]] : Scopes[2]
    0 : Script
        Myclass () : () 

I can no longer reference it with a variable as window[classname]. Grasping at straws I also tried [classname], global[classname] and Global[classname] and this[classname] and script[classname] but that does not work.

In ES6, how do I test if it is already loaded when the classname is in a variable ? This is probably something really easy, but it is eluding me.

Thanks in advance

This is how ES6 works... To avoid polluting the global object (here window ), your JavaScript code does not create global properties anymore (unless you are explicit). In ES5, these properties were created automatically when using var or function in the global scope. With let , const or class , nothing happens. Consider this example:

// ES5

var foo;

function qux() {}

console.log('foo' in window); // true
console.log('qux' in window); // true

// ES6

let bar;
const baz = '';

class Quux {}

console.log('bar' in window); // false
console.log('baz' in window); // false
console.log('Quux' in window); // false

window.bar = bar;
window.baz = baz;
window.Quux = Quux;

console.log('bar' in window); // true
console.log('baz' in window); // true
console.log('Quux' in window); // true

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