`
webcenterol
  • 浏览: 939288 次
文章分类
社区版块
存档分类
最新评论

Private Members in JavaScript

 
阅读更多

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

分享到:
评论

相关推荐

    AJAX资料(基础或中级水平的请看,对高手的帮助不大)

    压缩包内文档名如下: Core JavaScript 1.5 Guide Javascript面向对象 ...Private Members in JavaScript prototype手册 深入理解JavaScript闭包 悟透javascript(很好) 详解Javascript 中的this指针

    JavaScript的public、private和privileged模式

    在探讨JavaScript编程中,公共(public)、私有(private)和特权(privileged)模式是面向对象编程中用于管理对象内部成员的重要概念。JavaScript虽然是基于原型的语言,但它同样可以实现类似面向对象语言中的封装...

    如何在JavaScript对象中嵌入私有成员.doc

    1. 为何使用私有成员(Private Members) 私有成员的主要目的是限制对对象内部状态的访问。这在以下场景中尤为重要: - **数据安全性**:防止外部代码意外或恶意地改变对象的状态。 - **封装**:隐藏实现细节,...

    JavaScript 设计模式学习 Singleton

    // Everything returned in the object literal is public, but can access the members in the closure created above. return { // Public method. stringToArray: function(str, delimiter, stripWS) { if ...

    对javascript继承的理解

    例如,它无法实现私有成员(private members),因为所有的属性和方法最终都会暴露给子类。此外,虽然可以模拟静态方法和属性,但它们并不是真正意义上的静态,因为它们实际上是绑定到构造函数而不是类本身。 ES6...

    docme:从您项目的 jsdocs 生成与 github 兼容的 API 文档并将它们添加到您的自述文件中

    安装 npm install docme用法 docme <readme> <docme> -- <jsdoc> Generates jsdocs for non-private members of the project in the current folder. It then updates the given README with the githubified ...

    茶楼管理系统

    String sql = "INSERT INTO members(name, phone, balance) VALUES(?, ?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, this.name); pstmt.setString(2, this.phone); pstmt.setDouble(3, ...

    chat-adv-service:通过Google AppsScripts与聊天服务进行交互

    入门创建有权访问聊天API的服务帐户添加ChatService与库ID项目1XDYAGcUoblJ073Kjveni2WOZHpKLYE8qlYMkeHViavLXvsKnBIl1DR2A 将privateKey和issuerEmail发送到ChatService.init方法返回的对象具有Spaces , Members和...

    python3.6.5参考手册 chm

    The json module: JavaScript Object Notation The plistlib module: A Property-List Parser ctypes Enhancements Improved SSL Support Deprecations and Removals Build and C API Changes Port-Specific ...

    2022年PHP面试题.doc

    - ASP(Active Server Pages)使用VBScript或JavaScript作为脚本语言,易于学习,但性能相对较低。 - PHP(Hypertext Preprocessor)跨平台,语法简洁,支持多种数据库,并且完全免费,适合快速开发。 - JSP...

    基于Java和mysql的聊天系统

    私聊涉及两个用户之间的消息传递,可以通过创建`private_chats`表来存储每条聊天记录,记录`sender_id`、`receiver_id`和`message`等信息。群聊则需要`groups`表来存储群组信息,`group_members`表记录用户与群组的...

    NodeJS:Node.js编程语言

    // public members } } 模块图案结构 var Calculator = function ( ) { // private member var elDom = document . getElementById ( 'el' ) ; return { // expose public member add : function ( x ,

    php json_encode与json_decode详解及实例

    例如,类`Foo`的`public_ex`会被编码,而`private_ex`、`protected_ex`以及常量`ERROR_CODE`和方法`getErrorCode()`则不会。 四、`json_decode` `json_decode`函数将JSON字符串转换为PHP的数据结构。默认情况下,它...

    php面试题(PHP软件工程师面试宝典)

    - 支持多种脚本语言如 VBScript 和 JavaScript; - 可以在 Windows 平台上无缝集成 IIS; - 提供了强大的 COM 组件支持,便于创建复杂的应用程序。 - **缺点:** - 依赖于 Windows 和 IIS,跨平台性差; - 性能...

    FinalPOO:面向对象的东方节目总决赛

    而标签“TypeScript”表明这个项目使用了TypeScript语言,它是JavaScript的一个超集,提供了静态类型检查和现代语言特性,如类、接口和泛型,极大地增强了代码的可维护性和可靠性。 在TypeScript中,面向对象的核心...

Global site tag (gtag.js) - Google Analytics