Private member in JavaScript

Source: Internet
Author: User

JavaScript is the most misunderstood programming language in the world. Some people think that it does not have the ability to "hide information", because JavaScript objects do not have private variables and methods. This is a misunderstanding. JavaScript objects can have private members. Let's take a look at how to do this. ( Note: JavaScript does not really possess private, public, and other OOP features. These private, public, and privileged features are mentioned in this article, it uses other JavaScript features (see the "closure" section in this article) to "simulate" it. If you are interested, you can search for related articles. Of course, you can ignore these articles and use them as real OOP. Have fun !)


JavaScript is built on objects. Arrays are Objects, functions are Objects, and Objects are also Objects. So what is an object? An object is a set of "name: value" pairs (name-value pair. The name is a string, but the value can be a string, value, Boolean, or object (including arrays and functions ). Objects are usually implemented using hash tables so that they can be quickly valued.

If the value is a function, we can treat it as a "method ". When a method of an object is executed, the variable this is set to the object itself. In this way, you can use this variable to access the instance of the object.

You can use constructor to create an object. The constructor is a function with initialization objects. The constructor provides features and functions similar to the "class" in other languages, including static variables and methods.


All members of an object are public members. Any function can access, modify, or delete these members. You can also add new members. There are two main methods to add members to an object:

Through the constructor

This method is generally used to initialize the public variables of the object instance. The this variable of the constructor is used to add members to an object:

function Container(param) {  this.member = param;}

Construct a new object:

var myContainer = new Container('abc');

Then, the public variable myContainer. member has the value 'abc '.


This method is usually used to add public methods. When the object itself searches for a member but does not find it, it uses the prototype member of the constructor. This prototype mechanism implements the so-called "inheritance" for Object-Oriented objects, and also saves memory. Add a method to all objects created from the same constructor. You only need to add a function to the prototype of the constructor:

Container.prototype.stamp = function (string) {  return this.member + string;}

Then we can call this method:


Return 'abcdef '.


Private Members are created by the constructor. Usually, the constructors use the variables and function parameters declared by var to become private members.

function Container(param) {  this.member = param;  var secret = 3;  var self = this;}

This constructor creates three private instance variables: param, secret, And self.

function Container(param) {  function dec() {   if (secret > 0) {     secret -= 1;     return true;   } else {     return false;   }  }  this.member = param;  var secret = 3;  var self = this;}

Private method dec checks the instance variable secret. If it is greater than 0, auto-minus 1 and returns true; if it is less than 0, false is returned. In this way, the dec function of the object created by the framework can only be used three times.

By convention, we have created a private variable self. You can use a private method to access the object itself. However, this is only an option, because an error occurs in ECMAScript Language Specification, which makes the internal function's this variable set to an error value.

Public methods ( Note: The methods created through prototype mentioned above) cannot call private methods. Therefore, to use private methods, we need to introduce the privileged method ).


A privileged method can access private variables and methods, and it can be accessed by public methods and the outside world. You can delete or replace a privileged method, but you cannot modify it, nor force it to discard its own secret ( note: the original article is so, it may refer to its privilege, for more information, see ).

The privileged method is created in the constructor through this.

function Container(param) {  function dec() {   if (secret > 0) {     secret -= 1;     return true;   } else {     return false;   }  }  this.member = param;  var secret = 3;  var self = this;  this.service = function () {   if (dec()) {     return self.member;   } else {     return null;   }  };}

Service is a privileged method. The first three calls to myContainer. service () will return 'abc', and then return null. The service calls the private method dec to access the private variable secret. Other objects and methods can access the service, but cannot directly access private members.


The existence of this public, private, and privileged Member mode is due to the internal mechanism of JavaScript: closure. This means that an internal function can always access the variables and parameters of its external function, even if the external function has returned. This is a very powerful feature of JavaScript. There are no books on JavaScript programming to show how to use it, and none of them even mention this.

Private and privileged members can only be created during object initialization, while public members can be added at any time.

Mode public
function Constructor(...) {  this.membername = value;}Constructor.prototype.membername = value;
function Constructor(...) {  var self = this;  var membername = value;  function membername(...) {...}}

Note: This code:

function membername(...) {...}

In fact, it is a simple way to write the following code:

var membername = function membername(...) {...};
function Constructor(...) {  this.membername = function (...) {...};}

This article by Douglas Crockford laid the foundation for us to write a better JavaSciprt program and created a more rational Object-oriented Application and framework. As the translation was about to be completed, I was surprised to find a link to the Chinese version of this article on the author's website. Good thing! More and more Chinese people are paying attention to these technologies. Although I have already done some work, I hope you will benefit from this article. We also hope that more people can input original and translated front-end technical articles. when most people are impetuous, we need more basic work. There are not many articles per Monday and many articles per year. Just start!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.