JavaScript/Access control
Access Control
[edit | edit source]JavaScript does not provide a direct means to control access to internal variables, however, it is possible to restrict access to some variables.
By default, variables within an object are public and can be modified anywhere in the code. As such, any programmer that uses the code in the future may change the internal state of the object unexpectedly, which has the potential for problems. While the easiest protection against this is to properly document your code (e.g. comments showing how to use the object), there are cases where you want to block direct access to a variable.
To declare and use a variable as private, there are two steps required:
- Declare a new variable within the constructor using the var statement.
- Create an anonymous function within the constructor, and assign it as a method for an object.
The example below shows a private field being used:
function MyObject() {
this.publicNumber = 10; // Public field.
var privateNumber = 20; // Private variable.
this.getPrivateNumber = function() {
return privateNumber;
}
}
testObject = new MyObject();
var privateNumber is normally a local variable that only exists within the function. As you can see, it is accessed in this.getPrivateNumber(), which is an anonymous function, attempting to access it directly would result in an error. Since this anonymous function is declared in the constructor, it can use and modify the local variables declared in function MyObject, and keeps a reference to the variable even when the function returns. The anonymous function is bound to an instance of the object, and creating a new MyObject will create a new anonymous function that refers to the new privateNumber.