Private Members in JavaScript

來源:互聯網
上載者:User

標籤:str   put   modify   memory   info   ann   init   public   static   

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 have private instance variables and methods. But thisis a misunderstanding. JavaScript objects can have private members.Here‘s how.

Objects

JavaScript is fundamentally about objects. Arrays areobjects. Functions are objects. Objects are objects. So what areobjects? Objects are collections of name-value pairs. The names arestrings, and the values are strings, numbers, booleans, and objects(including arrays and functions). Objects are 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 is invoked, the this variable is setto the object. The method can then access the instance variablesthrough the this variable.

Objects can be 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 are all public members. Anyfunction can access, modify, or delete those members, or add newmembers. There are two main ways of putting members in a newobject:

In the constructor

This technique is usually used to initialize public instancevariables. The constructor‘s this variable is 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 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‘s prototype 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 are 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 that = this;}

This constructor makes 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 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 that = 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 be used to make this object limited to three uses.

By convention, we make a private that variable. 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 causes this to be set incorrectly for inner functions.

Private methods cannot be 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 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.

Privileged methods are 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 that = this;    this.service = function () {        return dec() ? that.member : null;    };}

service is a privileged method. Calling myContainer.service() will return ‘abc‘ the first three times it is called. After that, it will 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 not allow direct access to the private members.

Closures

This pattern of public, private, and privileged members is possible because JavaScript has closures. 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 it. Most don‘t even mention it.

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

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

}
Constructor.prototype.membername = value;

Private
function Constructor(...) {
var that = 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.