ES6 classes have inner names
This blog post explains that classes have lexical inner names, just like named function expressions.
The inner names of function expressions
You may know that function expressions have lexical inner names:
const fac = function me(n) {
if (n > 0) {
// Use inner name `me` to
// refer to the function
return n * me(n-1);
} else {
return 1;
}
};
console.log(fac(3)); // 6
The name me
of the named function expression becomes a lexically bound variable that is unaffected by which variable currently holds the function.
The inner names of classes
Interestingly, ES6 classes also have lexical inner names that you can use in methods (constructor methods and regular methods):
class C {
constructor() {
// Use inner name C to refer to class
console.log(`constructor: ${C.prop}`);
}
logProp() {
// Use inner name C to refer to class
console.log(`logProp: ${C.prop}`);
}
}
C.prop = 'Hi!';
const D = C;
C = null;
// C is not a class, anymore:
new C().logProp();
// TypeError: C is not a function
// But inside the class, the identifier C
// still works
new D().logProp();
// constructor: Hi!
// logProp: Hi!
(In the ES6 spec the inner name is set up by the dynamic semantics of ClassDefinitionEvaluation.)
Acknowledgement: Thanks to Michael Ficarra for pointing out that classes have inner names.
Comments
Post a Comment