[Updated] private member in Javascript

Source: Internet
Author: User
Private Members in javascriptjavascript private member

Douglas crockford
Www.crockford.com

Translation: Yuan Xiaohui (blog.csdn.net/uoyevoli /)

Javascript is the world's most misunderstood programming language. Some believe that it lacks the propertyInformation HidingBecause objects cannot have private instance variables and methods. But this is a misunderstanding. Javascript objects can have private members. Here's how.

Javascript is the most misunderstood language in the world. Some people think that it lacks the ability to hide information because its object cannot have private variables and methods. But this is a misunderstanding. Javascript objects also have private members. The method is here.

Objects

Object

Javascript is fundamentally aboutObjects. Arrays are objects. functions are objects. objects are objects. So what are objects? Objects are collections of name-value pairs. the names are strings, and the values are strings, numbers, booleans, and objects (including arrays and functions ). objects are usually implemented as HashTables so values can be retrieved quickly.

Javascript is rooted in objects. Arrays are objects, functions are objects, and objects are objects. So what is an object? An object is a set that contains the ing of "name-value. The name is a string, and the value can be a string, number, logical value or object (including arrays and functions ). Objects are usually implemented using hash tables to quickly obtain values.

If a value is a function, we can consider itMethod. When a method of an object is invoked,ThisVariable is set to the object. The method can then access the instance variables throughThisVariable.

If a "value" is a function, we call it a method. When an object's method is called,This object is assigned to thisVariable. In this way, you can use this to access the variable of the object instance.

Objects can be producedConstructors, Which are functions which initialize objects. constructors provide the features that classes provide in other versions ages, including static variables and methods.

Objects can be generated by constructors, which are used to initialize objects. The constructor assumes the role of "class" in other languages, and also provides a means to define static variables and methods.

Public

Public

The members of an object are allPublicMembers. Any function can access, modify, or delete those members, or add new members. There are two main ways of putting members in a new object:

All members of an object are public members. Any function can access, modify, or delete these Members or add new members. There are two ways to add members to a new object:

In the constructor

In the constructor

This technique is usually used to initialize public instance variables. The Constructor'sThisVariable 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');

ThenMycontainer. MemberContains'Abc'.

This technique is usually used to initialize public instance variables. The constructor uses the this variable to add members to an object.

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

If we construct a new object

var myContainer = new Container('abc');

SoMycontainer. MemberInclude'Abc'

In the prototype

In prototype

This technique is usually used to add public methods. When a member is sought and it isn' t found in the object itself, then it is taken from the object's constructor'sPrototypeMember. The prototype mechanic 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'sPrototype:

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

So, we can invoke the Method

myContainer.stamp('def')

Which produces'Abcdef'.

This technique is usually used to add a public method. When a (javascript interpreter) encounters an object member and finds that it does not exist in the object itself, it will go to the prototype of the object constructor. This prototype mechanism can be used to implement inheritance. It also occupies memory. If you want to add a method to all objects generated by a constructor, you only need to add this method to the prototype of the constructor.

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

We call this method

myContainer.stamp('def')

Returns'Abcdef '.



Private

Private

PrivateMembers are made by the constructor. OrdinaryVaRS and parameters of the constructor becomes the private members.

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

Private Members are generated by constructors. The parameters of common (VAR defined) variables and parameter constructors become private members.

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


This constructor makes three private instance variables:Param,Secret, AndSelf. They are attached to the object, but they are not accessible to the outside, nor are they accessible to the object's own public methods. they are accessible to private methods. private methods are 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 self = this;
}

This constructor generates three private instance variables: Param, secret, And self. They belong to objects, but they are invisible to the outside, and their own public methods are invisible. They are visible to private methods. The private method is the internal function of the constructor.

function Container(param) {

function dec() {
if (secret > 0) {
secret -= 1;
return true;
} else {
return false;
}
}

this.member = param;
var secret = 3;
}

The private MethodDecExaminesSecretInstance variable. If it is greater than zero, it decrementsSecretAnd returnsTrue. Otherwise it returnsFalse. It can be used to make this object limited to three uses.

The private method dec checks the secret value of the instance variable. If it is greater than 0, the value is reduced and true is returned. Otherwise, false is returned. It can be used to limit that this object can be used only three times.

By convention, we make a privateSelfParameter. This is used to make the object available to the private methods. This is a workaround for an error in the ecmascript language specification which causesThisTo be set incorrectly for inner functions.

According to the Convention, we generate a private self variable to allow the private method to access the object itself. This is a work und. The root cause of this is an error in the ecmascript language specification, which leads to an error in the internal function's this variable. (Note: Is that true? According to my test, it seems that this self variable is not needed)

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

Private methods cannot be called by public methods. To make private functions work, we need to introduce the privileged method.

Privileged

Privilege

APrivilegedMethod is able to access the private variables and methods, and is itself accessible to the public methods and the outside. it is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.

A privileged method can access private variables and methods, and it can be accessed by both public and external methods. You can delete or replace a privileged method, but cannot change it or force it to discard its own secret.

Privileged methods are assignedThisWithin the constructor.

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 ()){
// Translator's note: Based on my experiments
// You can use this. member here.
Return self. member;
} Else {
Return NULL;
}
};
}

The privileged method is assigned a value through this in the constructor.

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;
}
};
}

ServiceIs a privileged method. CallingMycontainer. Service ()Will return'Abc'The first three times it is called. After that, it will returnNull.ServiceCallthe privateDecMethod which accesses the privateSecretVariable.ServiceIs available to other objects and methods, but it does not allow direct access to the private members.

Service is a privileged method. The first three calls to mycontainer. Service () will return'Abc', And then it returns NULL. The service calls the private DEC method, and the DEC method accesses the private secret variable. Service is visible to other objects and functions, but it does not allow direct access to private members.

Note:

Is this necessary? According to my experiments (IE6 and ff1.5.0.3), the following code is normal:

Function container (PARAM ){

This. Member = Param;
VaR secret = 3;
VaR self = this;

This. Service = function (){
If (secret> 0 ){
Secret-= 1;
Return this. member;
} Else {
Return NULL;
}
};
}


Closures

Closure

This pattern of public, private, and privileged members is possible because JavaScript hasClosures. What this means is that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. this is an extremely powerful property of the language. there is no book currently available on JavaScript programming that shows how to exploit. most don't even mention it.

This mode of public, private, and privileged is probably because JavaScript has closures (Closures). Closure means that an internal function can always access the variables and parameters of its outer function, even if the outer function has already returned. This is an extremely powerful feature of JavaScript. At present, there is no book on how to use JavaScript programming. In fact, most of them have no reference to it.

Private and privileged members can only be made when an object is constructed. Public members can be added at any time.

Private and privileged members can only be generated when an object is constructed. Public members can be added at any time.

Patterns

Mode

Public

FunctionConstructor(...){

This. Membername = Value ;

}
Constructor. Prototype.Membername=Value;

Private

FunctionConstructor(...){

VaR self = this;
VaR Membername = Value ;

FunctionMembername(...){...}

}

Note: The function statement

FunctionMembername(...){...}

Is shorthand

VaRMembername= FunctionMembername(...){...};


Note:

FunctionMembername(...){...}

Is a simple form of the following statements:

VaRMembername= FunctionMembername(...){...};


Privileged

Function Constructor(...){

This. Membername = Function (... ){... };

}

Copyright 2001 Douglas crockford. All Rights Reserved wrrrldwide.


Copyright

<End>

Link: http://www.crockford.com/javascript/private.html

Yuan Xiaohui translation @ 2006-5-19


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.