Reputation: 31
I've tried to reload a javascript class file and get the following console feedback:
'Uncaught SyntaxError: redeclaration of 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>
test.class.js
class Test{
sayHello(){
return 'hello';
}
}
let _test = new Test();
console.log(_test.sayHello());
Any ideas? Thanks!
Upvotes: 3
Views: 1074
Reputation: 1624
In your class definition do this:
var myClassTest = class Test{
sayHello(){
return 'hello';
}
}
and then the definition should be:
let _test = new myClassTest(); // as long as it is inside a block of code, if it is in as a global you should use var too to avoid redeclaration issues.
The problem was that the class object was being redeclared more than once and we solved it just by assigning it to a var declaration, which allows redeclarations.
Upvotes: 0