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. 15天玩转redis —— 第四篇 哈希对象类型

    redis中的hash也是我们使用中的高频数据结构,它的构造基本上和编程语言中的HashTable,Dictionary大同小异,如果大家往后有什么逻辑需要用 Dictionary存放的话,可以根据场 ...

  2. Get a List of Keys From a Dictionary in Both Python 2 and Python 3

    http://askubuntu.com/questions/656610/trying-to-install-mysql-connector-for-python-3?rq=1 trying to ...

  3. Verilog学习笔记简单功能实现(四)...............译码器和编码器

    这里以简单的3-8译码器和8-3编码器为例: module decoder3_8(a,out); :]a; :]out; 'b1<<a;/*把最低位的1左移in位(根据in口输入的值)并赋 ...

  4. RDBMS架构的开源DW/DSS引擎列表

    因为笔者早期以oracle为主要RDBMS进行设计和优化,所以几乎即使单表超过5000w,多张超过300万以上的表做任意复杂的统计和风控计算都没出过性能问题.如今全面mysql为主线或者说open s ...

  5. 解决asp.net动态压缩

    本来想写一个网站优化的系列(前端到后端的数据库,垂直优化到分布式,后面会补上),但没有时间(借口),今天就总结一下前几天优化网站的过程. 网站优化重点在于找出出现性能问题的地方,往往是解决方案很简单, ...

  6. 为友盟消息推送开发的PHP SDK(composer版):可以按省发Android push

    一直以来APP希望按省市县推送Android push,只能自己分析用户经纬度,打tag发送. 现在终于有服务商提供了. 友盟消息推送 可以“按省推送”,很方便. 我为友盟做了PHP SDK(comp ...

  7. Captain Icon – 350+ 有趣的矢量图标免费下载

    Captain Icon 是一套一个惊人的免费图标集,包含350+有趣的矢量图标,可以缩放到任意大小而不会降低质量.图标的类别很丰富,有设计,体育,社会,天气等很多类别.提供 EPS.PSD.PNG. ...

  8. 经典网页设计:20个与众不同的国外 HTML5 网站

    大家都都知道, HTML5 具备所有最新的技术和功能,帮助我们创造平滑过渡,花式图像滑块和动画.如果你正在考虑使用HTML5 来设计自己的网站,那么这个集合能够帮助你. 在过去的10年里,网页设计师使 ...

  9. 经典案例:那些让人赞不绝口的创新 HTML5 网站

    在过去的10年里,网页设计师使用 Flash.JavaScript 或其他复杂的软件和技术来创建网站.但现在你可以前所未有的快速.轻松地设计或创造互动的.有趣好看的网站.如何创建?答案是 HTML5 ...

  10. aBowman >>可以运用到自己博客上的小插件

    大家进入我的博客会发现页面右边有一只小狗这部分.这个就是我用在上面的 一个小插件.插件网址是:http://abowman.com/google-modules/,这上面有很多的小插件,可以直接运用到 ...