JavaScript Patterns 5.3 Private Properties and Methods
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
- 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.
- 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的更多相关文章
- 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, ...
- JavaScript Patterns 5.4 Module Pattern
MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...
- JavaScript Patterns 6.7 Borrowing Methods
Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...
- JavaScript Patterns 6.5 Inheritance by Copying Properties
Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...
- 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 ...
- 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 ...
- JavaScript Patterns 6.6 Mix-ins
Loop through arguments and copy every property of every object passed to the function. And the resul ...
- JavaScript Patterns 6.4 Prototypal Inheritance
No classes involved; Objects inherit from other objects. Use an empty temporary constructor function ...
- JavaScript Patterns 6.3 Klass
Commonalities • There’s a convention on how to name a method, which is to be considered the construc ...
随机推荐
- iOS阶段学习第四天笔记(循环)
iOS学习(C语言)知识点整理笔记 一.分支结构 1.分支结构分为单分支 即:if( ){ } ;多分支 即:if( ){ }else{ } 两种 2.单分支 if表达式成立则执行{ }里的语句:双 ...
- Win10 IoT C#开发 1 - Raspberry安装IoT系统及搭建开发环境
Windows 10 IoT Core 是微软针对物联网市场的一个重要产品,与以往的Windows版本不同,是为物联网设备专门设计的,硬件也不仅仅限于x86架构,同时可以在ARM架构上运行. The ...
- 【Java每日一题】20161206
package Dec2016; public class Ques1206 { public static void main(String[] args){ doSex(null); } publ ...
- BZOJ 1051 最受欢迎的牛 解题报告
题目直接摆在这里! 1051: [HAOI2006]受欢迎的牛 Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 4438 Solved: 2353[S ...
- Android总结篇系列:Android开发环境搭建
工欲善其事必先利其器. 1.安装并配置Java环境进入Java oracle官网,当前网址如下:http://www.oracle.com/technetwork/java/javase/downlo ...
- 定时任务服务 CronService使用说明
CronServiceInstaller.exe 部署安装程序 1.在打开该程序前务必设置为管理员运行 2.点击注册服务 3.检查服务是否开启,点击 services.msc, 打开系统服务列表 4 ...
- Close与Dispose的区别
Close与Dispose的区别: Close 是停业整顿,停业了,可以通过公关,再重开,物还是原来的物:只是关闭而已,没有释放真正的释放资源,可以重新打开:Close是关门Dispose是破产: D ...
- 推荐12款实用的 JavaScript 书页翻转效果插件
Flipbooks(书页)或者页面翻转已成为在网页设计中最流行的交互动画之一.他们可以用在 Flash,网页或者在线杂志中.使用书页动画或者页面翻转的网页设计效果方便人们展示他们的产品,作品或者其它内 ...
- 【JavaScript】Write和Writeln的区别
目录结构: Write和Writeln的区别 如何查看Writeln的换行效果 参考文章 Write和Writeln的区别 Write不可以换行,Writeln可以换行. 如何查看Writeln的换行 ...
- 用node-webkit把web应用打包成桌面应用
node-webkit是一个Chromium和node.js上的结合体,通过它我们可以把建立在chrome浏览器和node.js上的web应用打包成桌面应用,而且还可以跨平台的哦.很显然比起传统的桌面 ...