Encapsulation in JavaScript

Neeraj Singh

By Neeraj Singh

on October 12, 2009

JavaScript does not allow you to define a method as public or private. This is a limitation users need to get around to, because in real life you don't want to expose all methods as public method.

Here is a simple implementation of the case where you want to verify input code.

1function verifycode(code) {
2  console.log(code.length);
3  return code.length == 4 ? true : false;
4}
5
6function info(code) {
7  if (verifycode(code)) {
8    console.log(code + " is valid");
9  } else {
10    console.log(code + " is wrong");
11  }
12}
13
14info("abcd");
15info("rty");

In the above implementation anyone can call the method verifycode. Not good. Here is one way to fix this problem.

1var Lab = Lab || {};
2Lab = (function () {
3  var verifycode = function (code) {
4    console.log(code.length);
5    return code.length == 4 ? true : false;
6  };
7  return {
8    info: function (code) {
9      if (verifycode(code)) {
10        console.log(code + " is valid");
11      } else {
12        console.log(code + " is wrong");
13      }
14    },
15  };
16})();
17
18Lab.info("abcd");
19Lab.info("rty");
20Lab.verifycode("abcd"); //verifycode is private

Another way to solve the same problem would be to create a constructor function. Here is an implementation.

1function Lab(code) {
2  this.code = code;
3  var verifycode = function () {
4    return code.length == 4 ? true : false;
5  };
6  this.info = function () {
7    if (verifycode()) {
8      console.log(code + " is valid");
9    } else {
10      console.log(code + " is wrong");
11    }
12  };
13}
14new Lab("abcd").info();

Here is another way to solve the same problem. In this case I have moved all the public methods to prototype.

1function Lab(code) {
2  this.code = code;
3  this.verifycode = function () {
4    l = code.length;
5    return l == 4 ? true : false;
6  };
7}
8
9Lab.prototype.info = function () {
10  if (this.verifycode()) {
11    console.log(this.code + " is valid");
12  } else {
13    console.log(this.code + " is wrong");
14  }
15};
16
17new Lab("abcd").info();

If you liked this blog, you might also like the other blogs we have written. Check out the full archive.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, React.js, React Native, remote work,open source, engineering & design.