簡體   English   中英

Javascript ES6在全局范圍內而不是在窗口范圍內引用變量

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

我正在將代碼從ES5升級到ES6。 在ES5中,我通過創建一個新腳本來動態加載該函數,該腳本隨后異步加載該文件。 代碼如下:

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;
}

在ES5中,該函數加載在全局范圍內,在這種情況下為window。 我在字符串中有函數/類名,可以使用window [classname]引用該類,如上面的代碼所示。 在ES6中,我將調用和被調用函數更改為一個類。 現在,當它加載腳本時,它作為Myclass function()存在於全局作用域中,但不存在於窗口作用域中,如Chrome調試器中所示,如下所示:

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

我無法再使用window [classname]作為變量來引用它。 我也嘗試過使用[classname],global [classname]和Global [classname]以及this [classname]和script [classname],但這是行不通的。

在ES6中,當類名位於變量中時,如何測試它是否已加載? 這可能確實很容易,但卻使我難以理解。

提前致謝

ES6的工作方式是...為了避免污染全局對象(此處為window ),您的JavaScript代碼不再創建全局屬性(除非您是明確的)。 在ES5中,在全局范圍內使用varfunction時會自動創建這些屬性。 使用letconstclass ,什么都不會發生。 考慮以下示例:

// 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM