JavaScript is the world's most misunderstood programming language. Some believe that it lacks the property of information hiding because objects cannot have private instance variables and methods. But this is a misunderstanding. JavaScript objects can have private members. Here's how.
Objects
JavaScript is fundamentally about objects. 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.
If a value is a function, we can consider it a method. When a method of an object is invoked, the this variable is set to the object. The method can then access the instance variables through the this variable.
Objects can be produced by constructors, which are functions which initialize objects. Constructors provide the features that classes provide in other languages, including static variables and methods.
Public
The members of an object are all public members. 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:
In the constructor
This technique is usually used to initialize public instance variables. The constructor's this variable 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');
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 parameter. 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 () {
if (dec()) {
return that.member;
} else {
return 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.
Patterns
Public
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 Douglas Crockford. All Rights Reserved Wrrrldwide.
转载声明: 本文转自 http://javascript.crockford.com/private.html
分享到:
相关推荐
压缩包内文档名如下: Core JavaScript 1.5 Guide Javascript面向对象 ...Private Members in JavaScript prototype手册 深入理解JavaScript闭包 悟透javascript(很好) 详解Javascript 中的this指针
Network Security:Private Communication in a Public World 第二版
#region private members 调用数据访问层统一数据访问方式 private static abstractdalfac【tor】y fac【tor】y abstractdalfac【tor】y choosefac【tor】y ; private static iclassservice classservice fac...
网络安全经典教材,第五版,pdf.是许多国外大学研究生的网络安全课的教材。
Gradient Inversion Attack Leaking Private Labels in Two-Party Split Learning_两方分裂学习中泄漏私有标签的梯度反转攻击.pdf
avaScript: Best Practice Kindle ...JavaScript’s New Private Class Fields, and How to Use Them by Craig Buckler This book is for all front-end developers who wish to improve their JavaScript skills.
wiz-private wiz-private
ProtectJS, 在JavaScript中,private 方法的&属性 protectjs/保护 JS 方法/函数将 private 方法添加到JavaScript中的对象一直是一件非常困难的事情,因为JavaScript并不完全支持它。 相反,我们将函数放在构造函数中...
PRIVATE
Private equity can be described as ‘investments in private companies in privately negotiated transactions’. This means that private equity is an asset class that is normally opaque, illiquid and ...
private
Network Security: Private Communication in a Public World, Second Edition By Charlie Kaufman, Radia Perlman, Mike Speciner ............................................... Publisher: Prentice Hall ...
Private Shell。Private Shell。Private Shell。Private Shell。
Introduce to Microsoft Virtual Machine Manager 2008 R2 in Private Cloud
instagram_private_api, 用于访问 Instagram API private的python 库 Instagram private APIInstagram private API的python 包装,没有 3rd 方依赖项。 同时支持应用程序和网络 api 。 概述当他们在开发人员访问中夹...
This is a private thing please dong download . ..............................................................
公共/私有变量和方法通过一个简单的的例子,来展示如何使用JavaScript在类里面创建私有变量和方法
private doc private doc
oracle_private oracle_private
Microsoft Private Folder 1.0又名我的密码箱是一款功能超群的加密软件,它界面友好,简单易用,采用先进的文件系统驱动技术及安全可靠的加密算法,真正意义上的实现了与 Windows文件系统的无缝集成,全面保证加密...