JavaScript 单例模式与方法链技术详解
1. 单例模式中的私有成员实现
在 JavaScript 里,使用闭包来实现单例模式中的真正私有成员是一种有效的方式。以 DataParser 为例,代码如下:
/* DataParser singleton, converts character delimited strings into arrays. */
/* Now using true private methods. */
GiantCorp.DataParser = (function() {
// Private attributes.
var whitespaceRegex = /\s+/;
// Private methods.
function stripWhitespace(str) {
return str.replace(whitespaceRegex, '');
}
function stringSplit(str, delimiter) {
return str.split(delimiter);
}
// Everything returned in the object literal is public, but can access the
// members in the closure created above.
return {
// Public method.
stringToArray: fun
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



