I'm using Google Chrome's Snippets (inside Dev Tools) for some JS development and testing.
When declaring ES6 classes, the console throws an
Uncaught SyntaxError: Identifier 'Foo' has already been declared at...
after the first time it was run.
class Foo {
constructor(val) {
this.bar = val;
}
}
var f = new Foo('myVal');
console.log(f.bar); // prints 'myVal'
I did some research and found out that wrapping the code in a block scope with {}
would help in avoiding this problem.
But when I do this, although the code runs without error, Chrome doesn't recognize any subsequent edits that I may do to my code.
So, if I changed the above code to the following:
{
class Foo {
constructor(val) {
this.bar = val;
}
}
}
var f = new Foo('myVal');
console.log(f.bar); // prints 'myVal'
So far everything works fine.
Now, I realize that there is a problem with my class and I change the code to the following:
{
class Foo {
constructor(val) {
this.bar = 'MyHardcodedVal'; // Here is the changed code
}
}
}
var f = new Foo('myVal');
console.log(f.bar); // STILL prints 'myVal'
As you can see, the edits I made to my class are not taking effect.
It appears that Google Chrome has put my code in a sandbox that is immune from my editing.
A way to look behind the scene and see what Google Chrome is doing is to introduce an intentional mistake into the code and then click on the source of the mistake that Chrome shows in the console. There you will see that the code for the class is still the old one and not changed at all, while the code that has been outside of the block scope is up to date.
I could always close the tab I am working in and open it again, but that isn't practical.
What am I doing wrong?
Is there a sane way to use Snippets for such tests?
Hope that makes sense!
Based off the comments, it sounds like the solution is to wrap the entire snippet in braces.
{
class Foo {
constructor(val) {
this.bar = 'MyHardcodedVal'; // Here is the changed code
}
}
var f = new Foo('myVal');
console.log(f.bar); // STILL prints 'myVal'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With