Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptHow to make variables private in Constructor functions in JavaScript ?

How to make variables private in Constructor functions in JavaScript ?

In Javascript there’s no specific way to make variables private in a Constructor function. If a variable is genuinely private, meaning it cannot be accessible from the outside. A constructor is a function that generates a new instance of a class, sometimes referred to as an “object.” A constructor’s job is to build an object and assign or set values for the properties of the object if they’re present. 

Let’s see how to make variables private in a constructor function in this article by looking at a few examples.

Example 1: There are two methods defined on the prototype, getElement, and setElement. The setElement doesn’t work. In the below example we create an object a with value 15, the same value is given to variable b to show that we can retrieve the value using getElement method but we cannot set or override the value by using setElement method, as args isn’t declared as a variable, it’s passed on to a new variable, so it stays private. By declaring the variables in the below manner, the variable cannot be further modified by any of its methods, it stays private.

Javascript




<script>
  function func(args) {
    var element = args;
  
    this.getElement = function () {
      return element;
    };
    this.setElement = function (input) {
      element = input;
    };
  }
  
  var a = new func(15);
  var b = a.getElement();
  console.log(b);
  a.setElement(5);
  var c = a.element;
  console.log(c);
</script>


Output:

15
undefined

Example 2: In the before method, a variable is declared and the value passed into the function is given to it. No new variable is declared to pass on the value of args in this example. So we can not change the value of a variable that’s not defined in the function. So setElement doesn’t help us create a new variable just like the previous example. As there is the perfect way to make variables private in a javascript constructor these methods can be used. It allows our values to not be changed in a javascript constructor. 

Javascript




<script>
  function func(args) {
    this.getElement = function () {
      return args;
    };
    this.setElement = function (input) {
      args = input;
    };
  }
  
  var a = new func(10);
  var b = a.getElement();
  console.log(b);
  a.setElement(5);
  var c = a.element;
  console.log(c);
</script>


Output:

10
undefined

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments