Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private properties in JavaScript ES6 classes

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" 
like image 902
d13 Avatar asked Mar 03 '14 20:03

d13


People also ask

What are private properties in JavaScript?

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.

How can you declare a private property of a class in JavaScript?

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.

Can JavaScript classes have properties?

“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().

Does JavaScript have private?

In its current state, there is no “direct” way to create a private variable in JavaScript.


1 Answers

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; } } 
like image 152
MetalGodwin Avatar answered Sep 17 '22 09:09

MetalGodwin