All object members are public in JavaScript.

var myobj = {

    myprop : 1,

    getProp : function() {

        return this.myprop;

    }
}; console.log(myobj.myprop);
// `myprop` is publicly accessible console.log(myobj.getProp());
// getProp() is public too

The same is true when you use constructor functions to create objects.

// all members are still public:

function Gadget() {

    this.name = 'iPod';

    this.stretch = function() {

        return 'iPad';

    };

}

var toy = new Gadget();

console.log(toy.name);
// `name` is public console.log(toy.stretch());
// stretch() is public

Private Members

Implement private members using a closure.

function Gadget() {

    // private member

    var name = 'iPod';

    // public function

    this.getName = function() {

        return name;

    };

}

var toy = new Gadget();

// `name` is undefined, it's private

console.log(toy.name);
// undefined // public method has access to `name` console.log(toy.getName());
// "iPod" 

Privileged Methods

it’s just a name given to the public methods that have access to the private members (and hence have more privileges).

In the previous example,  getName() is a privileged method because it has “special” access to the private property name.

Privacy Failures

• When you’re directly returning a private variable from a privileged method and this variable happens to be an object or array, then outside code can modify the private variable because it’s passed by reference.

function Gadget() {

    // private member

    var specs = {

        screen_width : 320,

        screen_height : 480,

        color : "white"

    };

    // public  function

    this.getSpecs = function() {

        return specs;

    };

}

var toy = new Gadget(), specs = toy.getSpecs();

specs.color = "black";

specs.price = "free";

console.dir(toy.getSpecs());

/*

color

"black"

price

"free"

screen_height

480

screen_width

320

*/

Solutions

  1. Principle of Least Authority (POLA):

Return a new object containing only some of the data that could be interesting to the consumer of the object.

  1. Another  approach,  when  you  need  to  pass  all  the  data,  is  to  create  a  copy  of  the specs object, using a general-purpose object-cloning function.

Object Literal and Privacy

var myobj;
// this will be the object ( function() { // private members var name = "my, oh my"; // implement the public part // note -- no `var` myobj = { // privileged method getName : function() { return name; }
}; }()); var myobj = ( function() { // private members var name = "my, oh my"; // implement the public part return { getName : function() { return name; }
}; }()); myobj.getName();
// "my, oh my"

Prototypes and Privacy

One drawback of the private members when used with constructors is that they are recreated every time the constructor is invoked to create a new object. To solve this you can add common properties and methods to the prototype property of the constructor.

function Gadget() {

    // private member

    var name = 'iPod';

    // public function

    this.getName = function() {

        return name;

    };

}

Gadget.prototype = ( function() {

        // private member

        var browser = "Mobile Webkit";

        // public prototype members

        return {

            getBrowser : function() {

                return browser;

            }
}; }()); var toy = new Gadget(); console.log(toy.getName());
// privileged "own" method console.log(toy.getBrowser());
// privileged prototype method 

Revealing Private Functions As Public Methods

var myarray;

(function () {

    var astr = "[object Array]",

        toString = Object.prototype.toString;

    // private method

    function isArray(a) {

        return toString.call(a) === astr;

    })

    // private method

    function indexOf(haystack, needle) {

        var i = 0,

            max = haystack.length;

        for (; i < max; i += 1) {

            if (haystack[i] === needle) {

                return i;

            }

        }

        return−1;

    }

    myarray = {

        // public methods

        isArray: isArray,

        indexOf: indexOf,

        inArray: indexOf

    };

}());

myarray.isArray([1, 2]); // true

myarray.isArray({
0: 1
}); // false myarray.indexOf(["a", "b", "z"], "z"); // myarray.inArray(["a", "b", "z"], "z"); //

Now if something unexpected happens, for example, to the public indexOf(), the private indexOf() is still safe and therefore inArray()will continue to work:

myarray.indexOf = null;

myarray.inArray(["a", "b", "z"], "z"); //

References: 

JavaScript Patterns - by Stoyan Stefanov (O`Reilly)

JavaScript Patterns 5.3 Private Properties and Methods的更多相关文章

  1. JavaScript Patterns 4.8 Function Properties - A Memoization Pattern

    Gets a length property containing the number of arguments the function expects: function func(a, b, ...

  2. JavaScript Patterns 5.4 Module Pattern

    MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...

  3. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

  4. JavaScript Patterns 6.5 Inheritance by Copying Properties

    Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...

  5. JavaScript Patterns 7.1 Singleton

    7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...

  6. OOP in JS Public/Private Variables and Methods

    Summary private variables are declared with the 'var' keyword inside the object, and can only be acc ...

  7. JavaScript Patterns 6.6 Mix-ins

    Loop through arguments and copy every property of every object passed to the function. And the resul ...

  8. JavaScript Patterns 6.4 Prototypal Inheritance

    No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...

  9. JavaScript Patterns 6.3 Klass

    Commonalities • There’s a convention on how to name a method, which is to be considered the construc ...

随机推荐

  1. oracle11g的standby性能分析报告statpack安装

    一般常见的分析standby database的性能问题的方法就是通过动态性能视图来判断,从11g开始,随着Active Data Guard功能的出现,早期的Statspack 工具可以在stand ...

  2. LCA---Tarjan算法

    本问题中Tarjan算法不需要设置栈和dfn,low标号,而是设置了并查集. 通过一次dfs遍历即可找出所有节点对的lca.将这样一次读取所有查询,计算一次后返回所有查询lca的算法称为离线算法 涉及 ...

  3. PowerDesigner中Table视图怎样同时显示Code和Name

    1.创建一个简单table视图步骤: 1)打开软件,创建model,选择Physical Data

  4. Droid@screen:在PC屏幕上显示Android手机屏幕

    这里介绍一款工具——Droid@screen,用来获取手机屏幕,显示在PC屏幕上.它集截图.录像等多种功能于一体. 安装 1.    下载地址:http://droid-at-screen.org/d ...

  5. Java接口之间的继承

    /** * Created by xfyou on 2016/11/3. * 多接口之间的继承 */ public class HorrorShow { static void u(Monster b ...

  6. 网上图书商城3--Book模块

    小技巧一:分页 ①PageBean<Book> findByCriteria(List<Expression> exprList, int pc)  --- 通用的查询方法(p ...

  7. GJM : Python简单爬虫入门(二) [转载]

    感谢您的阅读.喜欢的.有用的就请大哥大嫂们高抬贵手"推荐一下"吧!你的精神支持是博主强大的写作动力以及转载收藏动力.欢迎转载! 版权声明:本文原创发表于 [请点击连接前往] ,未经 ...

  8. linux常用命令之文件系统

    df df - report file system disk space usage 查看文件系统的使用清空 用法 df [-hi] [path] 选项 -h human readable ,以人类 ...

  9. Properties+重温Map+本地计数器

    昨天想写一个记账本,发现并不能把项目名称与内容关联起来,于是乎我想到了map,可是又不知道map储存到文件中又怎么读出来,幸好今天遇到了properties Properties是Hashtable的 ...

  10. Hashslider – 带有 Hash 标签功能的 jQuery 内容滑块

    Hashslider 实现了常见的 jQuery 滑块的功能,特别之处在于给 URL 加上了标签,因此你能够连接到滑块的某块内容.滑块的内容也可以从外部的 HTML 文件获取. 您可能感兴趣的相关文章 ...