Private members in JavaScript

Source: Internet
Author: User

Private members in JavaScript

Douglas Crockford
www.crockford.com

JavaScript is TheWorld's most misunderstood programming language. Some Believethat It lacks the property of information hiding becauseobjects cannot has private instance variable S and methods. But thisis a misunderstanding. JavaScript objects can has private members. Here's how.

Objects

JavaScript is fundamentally about objects. Arrays areobjects. Functions is objects. Objects is Objects. So what areobjects? Objects is collections of name-value pairs. The names arestrings, and the values are strings, numbers, Booleans, and objects (including arrays and functions). Objects is usually implemented ashashtables so values can be retrieved quickly.

If A value is a function, we can consider it a method. Whena method of an object was invoked, the this variable is setto the object. The method can then access the instance Variablesthrough the this variable.

Objects can produced by Constructors, which arefunctions which initialize Objects. Constructors provide the Featuresthat classes provide in other languages, including static Variablesand methods.

Public

The members of an object is all public. Anyfunction can access, modify, or delete those members, or add newmembers. There is both main ways of putting members in a newobject:

In the constructor

This technique was usually used to initialize public instancevariables. The constructor ' s this variable are used to AddMembers 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

This technique was usually used to add public methods. When a member is sought and it's isn ' t found in the object itself, then it's taken from the object's constructor ' s prot Otype member. The prototype mechanism is used for inheritance. It also conserves memory. To add a method to all objects made by a constructor, add a function to the constructor ' s prototype:

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

So, we can invoke the method

Mycontainer.stamp (' Def ')

which produces ' abcdef '.

Private

Private members is made by the constructor. Ordinary vars and parameters of the constructor becomes the private members.

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

This constructor makes three private instance variables: param, secret, and . They is attached to the object, but they is not accessible to the outside, nor is they accessible to the object ' s own p Ublic methods. They is accessible to private methods. Private methods is inner functions of the constructor.

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

The private method Dec examines the secret instance variable. If it is greater than zero, it decrements secret and returns true. Otherwise it returns false. It can used to make this object limited to three uses.

By convention, we do a private that variable. This was used to make the object available to the private methods. This was a workaround for an error in the ECMAScript Language specification which causes this to be set Incorrectl Y for inner functions.

Private methods cannot is called by public methods. To make private methods useful, we need to introduce a privileged method.

Privileged

A Privileged method is able to access the private variables and methods, and are itself accessible to the public m Ethods and the outside. It's possible to delete or replace a privileged method, but it's isn't possible to alter it, or to force it to give up its Secrets.

Privileged methods is assigned with this within the constructor.

function Container (param) {    function Dec () {        if (Secret > 0) {            Secret-= 1;            return true;        } else {            return false;        }    }    This.member = param;    var secret = 3;    var = this;    This.service = function () {        return Dec ()? That.member:null;}    ;}

Service is a privileged method. Calling Mycontainer.service () would return ' abc ' the first three times it is called. After that, it'll return null. Service calls the private Dec method which accesses the private secret variable. service is available to other objects and methods, but it does isn't allow direct access to the private members.

Closures

This pattern of public, private, and privileged are possible because JavaScript has closures. What's this means are that a inner function always have access to the VARs and parameters of their outer function, even after t He outer function has returned. This is a extremely powerful property of the language. There is the no book currently available on JavaScript programming that shows what to exploit it. Most don ' t even mention it.

Private and privileged members can are made when a object is constructed. Public members can is added at any time.

Patternspublic
function Constructor (...) ) {this
. membername = value ;

}
Constructor . prototype. membername = value ;

Private
function Constructor (... ) {
var = this;
var membername = value ;

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

}

note:the Function statement

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

is shorthand for

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

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

}

Copyright 2001 Douglascrockford. Allrights Reserved wrrrldwide.

Private members in JavaScript

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: info-contact@alibabacloud.com 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.