I try to check whether a "variable" in es6 is constant:
const a = 1;
function test() {
try {
a = 2;// throws an error
} catch (error) {
console.log(error)
}
}
test();
But when I use eval() function ,It doesn't throws an error.
const a = 1;
function test() {
try {
eval("a = 2;")// not throws an error
} catch (error) {
console.log(error)
}
}
test();
And I make the constant local, the function eval does throw an error as expected.
function test() {
try {
const a = 1;
eval("a = 2;")//throws an error
} catch (error) {
console.log(error)
}
}
test();
And when I use function eval() that cause it doesn't throw an error as expectd. What the functoin eval() have done here ? I run it in Node v6.2.2
const a = 1;
function test() {
try {
eval("");
a = 2; // will not throw an error
} catch (e) {
console.log(e)
}
}
test();
More interesting, I enclose eval() with if (false),it will not throw an error either.
const a = 1;
function test() {
try {
if (false) {
eval("");
}
a = 2; // will not throw an error
} catch (e) {
console.log(e)
}
}
test();
Anyone can tell me the reason?
Is this a bug in JavaScript?
And how can I catch the global constant variable changed error?