【发布时间】:2016-10-20 22:08:37
【问题描述】:
例如,看一下我对堆栈的简单实现:
var MyStack = (function() {
var min;
var head;
// Constructor
function MyStack() {
this.size = 0;
}
MyStack.prototype.push = function(val) {
var node = new Node(val);
if (typeof min === 'undefined' || val < min) {
min = val;
}
++this.size;
if (typeof head === 'undefined') {
head = node;
} else {
node.next = head;
head = node;
}
};
MyStack.prototype.pop = function() {
if (typeof head === 'undefined') {
throw new Error('Empty stack');
}
--this.size;
var data = head.data;
head = head.next;
return data;
};
MyStack.prototype.min = function() {
if (typeof min === 'undefined') {
throw new Error('Min not defined');
}
return min;
};
MyStack.prototype.peek = function() {
if (typeof head === 'undefined') {
throw new Error('Empty stack');
}
return head.data;
};
function Node(data) {
this.data = data;
this.next;
}
return MyStack;
})();
通过使用这种方法,我可以确保没有人能够(无意或有意)操纵“私有”字段,例如 min 和 head。我还可以使用不需要公开的私有函数,例如 Node()。
我已经读到这将使用更多内存,因为它必须为为 MyStack 创建的每个新对象维护一个额外的范围。它是否需要如此多的额外内存以至于这种方式是个坏主意?
我确实尝试通过使用原型而不是每次创建新对象时都创建函数来优化它。换句话说,我没有将函数包含在 MyStack 的构造函数中。
我的问题是,这是糟糕的设计吗?这种方法有什么重大缺陷吗?
【问题讨论】:
-
“模拟封装”是指“实现封装”吗?因为我看不出这不是封装。
标签: javascript closures