`
zjlovezj
  • 浏览: 28556 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

[转贴]Private Members in JavaScript

阅读更多

Private Members in JavaScript

 

Douglas Crockford
www.crockford.com

 

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.      //这和Java就很不同了!  private和public好像井水不犯河水,互不访问吗?(见下个红色段落)

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.

 
分享到:
评论

相关推荐

    javascript和VBScript调试工具v1.0 推荐

    然而,描述中提到该工具是从精易论坛转贴的,可能意味着它并非官方发布的版本,而是社区共享的资源。这意味着可能存在一些潜在的问题,比如缺少官方支持、更新滞后或存在安全风险。因此,在使用这样的第三方工具时,...

    论坛转贴 v1.0 JS版-源码.zip

    【标题】"论坛转贴 v1.0 JS版-源码.zip" 提供的是一个基于JavaScript的论坛转贴功能的源代码实现。JS版通常指的是使用JavaScript编程语言编写的版本,这表明该软件可能主要用于网页端,利用浏览器的JavaScript引擎...

    jquery的转贴功能实现

    在网页开发中,jQuery是一个非常流行的JavaScript库,它极大地简化了DOM操作、事件处理和Ajax交互等任务。在本主题中,我们将深入探讨如何利用jQuery实现“转贴”功能,这是一种常见的社交媒体分享功能,允许用户将...

    史上最全的转贴代码

    【标题】:“史上最全的转贴代码”通常指的是一个包含大量可复用代码片段或解决...实际的"史上最全的转贴代码"压缩包可能会涵盖更多其他编程语言和技术领域的代码,但在这个例子中,我们专注于JavaScript方面的知识。

    javascript 中对象的继承〔转贴〕

    for (var prop in source) { this[prop] = source[prop]; } return this; }; var obj = {}; obj.extend({ a: 1, b: 2 }); console.log(obj.a); // 输出 1 ``` **3.3 函数绑定** `prototype.js` 提供了 `...

    BFC UBB转贴器

    由于现在流行的转贴工具都是基于浏览器的,转换速度比较慢,还得打开浏览器才能使用(同时受到浏览器版本限制)。 <br> 而这个小程序则完全不依赖于浏览器,以BFC采集器的UBB转换模块为基础,转换速度超快,...

    易语言源码动网转贴.rar

    "动网转贴"这个主题可能指的是在论坛或者社交网络中实现帖子转发或分享的功能。 动网转贴的源码可能涉及到以下几个方面的知识点: 1. **网络通信**:在实现动网转贴功能时,首先需要与服务器进行交互,发送用户的...

    动网转贴.e.rar

    【标题】"动网转贴.e.rar"是一个压缩文件,很可能包含了有关动网论坛或社区的相关资源、数据或用户帖子的备份。动网是中国早期知名的网络论坛软件之一,提供了丰富的社区功能,允许用户发帖、回帖、互动等。这个...

    动易系统的论坛转贴工具

    《动易系统的论坛转贴工具详解与应用》 在互联网信息交流日益频繁的今天,论坛作为用户互动的重要平台,其内容分享与传播的作用不容忽视。动易系统的论坛转贴工具,便是为了解决用户在论坛间便捷分享内容而设计的一...

    Html处理软件、转贴工具(源代码)

    去除Html中的干扰码等(样例中以轻之国度的干扰码为例) 配置文件语法: 方法类型(整数) 最大匹配长度(整数) 字符串1(删除开头) 字符串2(删除结尾) 方法类型: 1:删除单行 2:删除行与行之间的

    易语言动网转贴.rar

    "动网转贴"可能是基于易语言编写的一个功能模块或者工具,用于在论坛或者网站之间转移帖子数据。由于压缩包文件名为“易语言动网转贴.rar”,我们可以推测这可能是一个软件开发资源,包含了一些源代码、教程或者是...

    东度极品论坛转贴工具

    东度极品论坛转贴工具东度极品论坛转贴工具

    电子政务-导电泡棉转贴装置.zip

    在“导电泡棉转贴装置”这个特定的场景下,我们可能是在讨论一种用于电子政务设备或系统中的特殊组件。 导电泡棉是一种具有导电性能的泡沫材料,通常用于电子设备的屏蔽、接地或防静电保护。在电子政务设备中,这种...

    动网转贴.zip易语言项目例子源码下载

    《易语言项目实例——动网转贴》 易语言,作为一种中文编程语言,以其独特的语法和易用性,深受广大编程爱好者尤其是初学者的喜爱。这个名为“动网转贴”的项目,是易语言编程实践中一个典型的例子,它为学习者提供...

    行业分类-设备装置-FPC吸附胶纸转贴组件.zip

    本压缩包文件"行业分类-设备装置-FPC吸附胶纸转贴组件.zip"主要关注的是FPC在实际应用中的一个重要环节——FPC吸附胶纸转贴组件。这个组件在FPC的制造和组装过程中起到关键作用,确保FPC能够稳定地固定在设备上,并...

    转贴一个网络设计的例子

    转贴一个网络设计的例子

    电子功用-导电胶配对模切对半转贴加工方法

    本篇将详细探讨“电子功用-导电胶配对模切对半转贴加工方法”,这是一种高效的生产工艺,旨在提高电子产品的性能和可靠性。 导电胶主要由导电填料(如金属颗粒)、树脂基体和添加剂组成。它的特性在于既能保持良好...

    易语言动网转贴

    "易语言动网转贴"是指使用易语言编写的一段代码或程序,主要用于在动网上实现帖子的转换或者迁移。动网可能是一个论坛或社区平台,转贴功能则是将某个地方的帖子复制到另一个地方,保持其内容完整。 在这个源码中,...

Global site tag (gtag.js) - Google Analytics