skip to content
Alvin Lucillo

Hard privacy on private prop

/ 1 min read

Private variables aren’t really inaccessible; you can do cimcumvention to access the values. But with “hard privacy” using pound sign, you can achieve true private values.

In the example below, using “hard privacy”, when accessing dynamic property, it shows undefined, and when accessing in normal way, it fails throws error at runtime.

class Test {
	private var1 = 10;
	#var1 = 10;
}
// No error at compile time and prints '10'
console.log(new Test()["var1"]); // prints '10'

// Error at compile time: Property 'var1' is private and only accessible within class 'Test'.
// No error at transpilation
// After JS files are run, it prints '10'
console.log(new Test().var1);

// Error at compile time: Property '#var1' does not exist on type 'Test'. Did you mean 'var1'?(2551)
// No error at transpilation
// After JS files are run, it prints 'undefined'
console.log(new Test()["#var1"]); // prints '10'

// Error at compile time: Property '#var1' is not accessible outside class 'Test' because it has a private identifier.
// Error at run time:  'Executed JavaScript Failed: Unexpected token ')''
console.log(new Test().#var1);