Is it possible to create private properties in ES6 classes?
Here's an example. How can I prevent access to instance.property
?
class Something { constructor(){ this.property = "test"; } } var instance = new Something(); console.log(instance.property); //=> "test"
The private keyword in object-oriented languages is an access modifier that can be used to make properties and methods only accessible inside the declared class. This makes it easy to hide underlying logic that should be hidden from curious eyes and should not be interacted with outside from the class.
Class fields are public by default, but private class members can be created by using a hash # prefix. The privacy encapsulation of these class features is enforced by JavaScript itself. Private members are not native to the language before this syntax existed.
“Class fields” is a syntax that allows to add any properties. For instance, let's add name property to class User : class User { name = "John"; sayHi() { alert(`Hello, ${this.name}!`); } } new User().
In its current state, there is no “direct” way to create a private variable in JavaScript.
Short answer, no, there is no native support for private properties with ES6 classes.
But you could mimic that behaviour by not attaching the new properties to the object, but keeping them inside a class constructor, and use getters and setters to reach the hidden properties. Note that the getters and setters gets redefine on each new instance of the class.
ES6
class Person { constructor(name) { var _name = name this.setName = function(name) { _name = name; } this.getName = function() { return _name; } } }
ES5
function Person(name) { var _name = name this.setName = function(name) { _name = name; } this.getName = function() { return _name; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With