SyntaxError: reference to undeclared private field or method #x
The JavaScript exception "reference to undeclared private field or method #x" occurs when a private name is used, but this private name is not declared in the class scope.
Message
SyntaxError: Private field '#x' must be declared in an enclosing class (V8-based) SyntaxError: reference to undeclared private field or method #x (Firefox) SyntaxError: Cannot reference undeclared private names: "#x" (Safari)
Error type
What went wrong?
Unlike normal string or symbol properties, which return undefined
if the property does not exist, private names are very strict and can only be legally accessed if they actually exist. Accessing an undeclared private name will result in a syntax error, while accessing a private name that is declared but doesn't exist on the object will result in a type error.
Examples
Undeclared private field
You cannot access a private field that is not declared in the class scope.
class MyClass {
doSomething() {
console.log(this.#x);
}
}
The same error occurs if you use the in
operator to perform a check on an undeclared private field.
class MyClass {
doSomething() {
console.log(#x in this);
}
}
These code are probably mistakes because it's impossible for #x
to exist on this
if it's not declared in the class scope. Note that you cannot dynamically add private properties to unrelated objects. You should either remove this code or declare the private field in the class scope.
class MyClass {
#x = 0;
doSomething() {
console.log(this.#x);
}
}