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 ...
随机推荐
- C++移位运算符
关于逻辑移位.算术移位可参见迅雷深大笔试题部分.的一道题. 以前看到C++标准上说,移位运算符(<<.>>)出界时的行为并不确定: The behavior is undefi ...
- C#编程总结(四)多线程应用
C#编程总结(四)多线程应用 多线程应用很广泛,简单总结了一下: 1)不阻断主线程,实现即时响应,由后台线程完成特定操作2)多个线程,完成同类任务,提高并发性能3)一个任务有多个独立的步骤,多个线程并 ...
- 背水一战 Windows 10 (6) - 控件 UI: 字体的自动继承的特性, Style, ControlTemplate
[源码下载] 背水一战 Windows 10 (6) - 控件 UI: 字体的自动继承的特性, Style, ControlTemplate 作者:webabcd 介绍背水一战 Windows 10 ...
- mysql---ENCODE警告
'ENCODE' is deprecated and will be removed in a future release. Please use AES_ENCRYPT instead ***** ...
- C#多线程学习笔记
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threa ...
- ahjesus 单词单数-复数相互转换C#
看codesmith内置的模板在生成存储过程的时候有单复数的转换,用相同的函数名实现了一个 public static class StringUtil { /// <summary> / ...
- 一行代码调用实现带字段选取+条件判断+排序+分页功能的增强ORM框架
问题:3行代码 PDF.NET是一个开源的数据开发框架,它的特点是简单.轻量.快速,易上手,而且是一个注释完善的国产开发框架,受到不少朋友的欢迎,也在我们公司的项目中多次使用.但是,PDF.NET比起 ...
- Lazyr.js – 延迟加载图片(Lazy Loading)
Lazyr.js 是一个小的.快速的.现代的.相互间无依赖的图片延迟加载库.通过延迟加载图片,让图片出现在(或接近))视窗才加载来提高页面打开速度.这个库通过保持最少选项并最大化速度. 在线演示 ...
- 从0开始学angularjs-笔记02
上一节课主要跟大家讲解了angularjs的几种特性和看了一个简单的双向绑定的例子.最近都没有时间写博客了....忙成狗呀...今天周末,在写一篇吧~~ 今天主要跟大家详细讲解一下angularjs的 ...
- 通过API找出Autodesk Vault中某个用户组可以访问的Vault
首先在Vault Explorer中可以这样查看和更改某个用户组有权访问的vault Tools –> Administration –> Global Settings –> Gr ...