I know there are several questions on valid identifier names, property names, reserved words etc., but there is some variation (and much verbosity) in the answers. I would just like to know the answer for a very specific case.
The reason for wanting to use the name eval
, is that this is for a node module that will actually evaluate code (in another language), so it feels like the most appropriate name.
So my question is:
Can I do this?
function Foo() { ... }
Foo.prototype.eval = function(args) { ... }
Or in ES6, this?
class Foo {
...
eval(args) { ... }
}
And what would be the drawbacks, assuming this is technically valid?
eval
isn’t a reserved word. It’s just a property on window
or whatever globalThis
is (e.g. global
on Node). There’s no reason why there can’t be a property with the same name on a different object (Foo
’s prototype).
All of these are valid, and all of these create a property with the key eval
on some object:
function Foo(){}
Foo.prototype.eval = function(){};
new Foo().eval();
class Foo{
eval(){}
}
new Foo().eval();
({
eval: function(){}
}).eval();
To go even further, even if eval
was a reserved word, all of these would still be valid. This is valid, because methods can actually have any name:
class Foo{
if(){}
}
new Foo().if();
({
if(){},
var(){},
for(){},
switch(){}
}).var();
You just can’t use them on their own, like const if = new Foo().if;
or const {if} = new Foo();
, if they’re reserved words. eval
would be fine here; it would just overwrite window.eval
.