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 ...
随机推荐
- Struts2之Struts2-2.5.5 Interceptor
Struts2-2.5.5版本是目前为止最新的版本了,相对于之前的2.3版本以及再之前的版本而言,新版本改动了很多. 好了,废话不多说,GO CODE! 基本jar包: web.xml核心配置,这里要 ...
- 瞬间读懂什么是互联网思维、大数据、O2O、众筹、红海
1.什么叫大数据? 某必胜客店的电话铃响了,客服人员拿起电话. 客服:必胜客.您好,请问有什么需要我为您服务? 顾客:你好,我想要一份…… 客服:先生,烦请先把您的会员卡号告诉我. 顾客:16846 ...
- Linux学习笔记15-YUM安装
rpm软件包缺点:需要手工解决软件包的依赖关系.使用YUM可解决该问题. YUM(Yellodog Updater, Modified)是一个RPM前端程序,主要目的是设计用来自动解决RPM的依赖关系 ...
- WPF钟表效果实现
WPF在样式定义和UI动画上面相对于以前的技术有了不少的提升,下面给出WPF技术实现钟表的效果: 1.Visual Studio新建一个WPF应用程序,命名为WpfClock,新建一个images文件 ...
- Aurelia – 模块化,简单,可测试的 JS 框架
Aurelia 是下一代 JavaScript 客户端框架,利用简单的约定来激发你的创造力.凭借其强大的专注于开发经验, Aurelia 可以使您不仅创造惊人的应用程序,同时也享受这个过程.它经过精心 ...
- Sortable – 简单灵活的 JavaScript 拖放排序插件
当需要在网站中添加拖放排序功能的时候,jQuery UI 的排序组件可能是最流行的解决方案.今天给大家介绍另一款简单灵活的 JavaScript 拖放排序插件——Sortable,它使用 HTML5 ...
- 【HTML5】<datalist>标签和<select>标签的比较
<select>标签: 注:该标签定义了下拉列表的实现 <select name = "location"> <option value = &quo ...
- (转)轻松学习JavaScript三:JavaScript与HTML的结合
摘自:http://blog.csdn.net/erlian1992 HTML中的JavaScript脚本必须位于<script>与</script>标签之间,JavaScri ...
- [js开源组件开发]loading加载效果
loading加载效果 由于程序和网络的原因,常常我们需要在交互的时候,给用户一个正在加载中的动画,于是,loading组件横空出世.不需要复杂的代码,也能完成大多数业务,这就是我做组件的原则. 效果 ...
- iOS上new Date出现Invalid Date的问题,
用angular的ngModel绑定time的时候,在安卓调试没问题,没想到在iOS上出现了NaN:NaN,后台丢过来的数据大概是这样的2016-03-08 20:14 然而问题就出在这个分隔符&qu ...