Access Control

Access Control

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.
Clipboard

To do:
Cleanup example; it's currently purely synthetic and arbitrary.

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.



  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.

JavaScript/Access_control
 



 

Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over $50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.
Taught Advanced Internet Marketing Strategies at the graduate level.


Manage research, learning and skills at defaultLogic. Create an account using LinkedIn or facebook to manage and organize your Digital Marketing and Technology knowledge. defaultLogic works like a shopping cart for information -- helping you to save, discuss and share.


  Contact Us