重新加载 javascript 类,(未捕获的语法错误:重新声明 let 'classname' )

问题描述 投票:0回答:1

我尝试重新加载 JavaScript 类文件并获得以下控制台反馈:

'未捕获的语法错误:重新声明 let Test'

<button id="reload">loadScript</button>

<script>

    let reloadBtn = document.getElementById('reload');
    reloadBtn.addEventListener('click', function(){
        
        let addonScripts = document.getElementById('js').querySelectorAll('.addon-script');
        
        addonScripts.forEach(function(s){
            s.remove();
        });
        
        loadScript('test.class.js', 'addon-script', function(){ console.log('script loaded'); });
    });
    
    
    
    
    function loadScript(url, styleClass, callback){

        var script = document.createElement("script");
        script.type = "text/javascript";
        script.classList.add(styleClass);

        if(script.readyState){  //IE
            script.onreadystatechange = function(){
                if(script.readyState == "loaded" ||
                    script.readyState == "complete"){
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else {  //Others
            script.onload = function(){
                callback();
            };
        }

        script.src = url;
        document.getElementById("js").appendChild(script);
    }
    
    
</script>
<div id="js"></div>

测试.class.js

课堂测试{

sayHello(){
    return 'hello';
}

}

let _test = new Test();

console.log(_test.sayHello());

有什么想法吗?谢谢!

javascript reload
1个回答
0
投票

在您的类定义中执行以下操作:

var myClassTest = class Test{

  sayHello(){
    return 'hello';
  }

}

那么定义应该是:

let _test = new myClassTest();

问题在于类对象被多次重新声明,我们只需将其分配给允许重新声明的 var 声明即可解决该问题。

© www.soinside.com 2019 - 2024. All rights reserved.