Skip to content

JavaScript private properties

  • by

There is no reserved keyword for private. A private access modifier is the principle of object-oriented programming to make properties and methods only accessible inside the declared class.

You can use it as a variable and Closures Or ES6 Classes in JavaScript

JavaScript private properties

simple example code use closure() to Create Private Properties in JavaScript.

<!DOCTYPE html>
<html>
<body>
  <script>

   (function one() {
    var a = 'Hello World Private ';

    // The scope of the outer function is accessible to this inner function.
    (function two() {
        console.log(a);
      })();
    })();

  </script>
</body>
</html>

Output:

JavaScript private properties

Use ES6 Classes to Create Private Properties in JavaScript.

Put the new properties within a class function Object() { [native code] }. We can utilize the getters and setters to access the hidden properties rather than attaching them to the object.

class Person {
    constructor(name) {
        var _name = name
        this.setName = function(name) { _name = name; }
        this.getName = function() { return _name; }
    }
}

Latest ECMAScript

class Something {
    #property;

    constructor(){
        this.#property = "test";
    }

    #privateMethod() {
        return 'hello world';
    }

    getPrivateMessage() {
        return this.#property;
    }
}

const instance = new Something();
console.log(instance.property); // It will show "undefined"
console.log(instance.privateMethod); // This will show "undefined"
console.log(instance.getPrivateMessage()); // This will show "test"

To access the public property from private property, use self.

var PersonModule = (function(){
    var self = {};

    var privateChangeNameToBob = function(){
        self.name = "World";
    };

    self.sayHello = function(){
        console.log("Hello " + self.name);
    };

    self.changeName = function(){
        privateChangeNameToBob();
    };
    self.name = "";

    return self;
})();
PersonModule.name = 'Test';
PersonModule.changeName();
PersonModule.sayHello();

Source: https://www.delftstack.com/howto/javascript/private-properties-in-javascript-using-es6-classes/

Do comment if you have any doubts or suggestions on this Js private topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading