Helllo
Today, we will discuss about private instance variables and methods in javascript.
Most of the time it is believed that javascript can not have the information hiding property but that is not true. Javascript objects can have private members.
JavaScript is about objects. Everything in it is an object. The this variable is set to an object whenever a method of the same object is invoked. This method can also access the instance variables using the this keyword. Objects can be created and initialized using constructors as well.
Public
Any function can access, modify, or delete the members of the object, or add new members. There are two ways of putting members in a new object:
In the constructor
The constructor's this variable is used to add members to the object.
function Container(param) {
this.member = param;
}
So, if we construct a new object
var myContainer = new Container('abc');
then myContainer.member contains 'abc'.
In the prototype
The prototype mechanism is used for inheritance. It is used to add public methods. It also conserves memory.
Container.prototype.stamp = function (string) {
return this.member + string;
}
myContainer.stamp('def')
// it produces 'abcdef'.
Private
Private members are made by the constructor.
function Container(param) {
this.member = param;
var secret = 3;
var that = this;
}
This constructor has three private instance variables: param, secret, and that. They are attached to the object, but they are not accessible to the outside, nor are they accessible to the object's own methods. They are accessible to inner functions of the constructor called the private methods.
function Container(param) {
function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3;
var that = this;
}
Patterns:
Public
function Constructor(...) {
this.membername = value;
}
Constructor.prototype.membername = value;
Private
function Constructor(...) {
var that = this;
var membername = value;
function membername(...) {...}
}
0 Comment(s)