【发布时间】:2015-06-30 00:29:48
【问题描述】:
var RPNCalculator = function() {
this.stack = [];
this.total = 0;
this.value = function() {
return this.total;
}
this.push = function(val) {
this.stack.push(val);
}
this.pop = function() {
this.stack.pop();
}
this.process = function() {
this.val1 = this.stack.pop();
this.val2 = this.stack.pop();
this.total = 0;
}
this.plus = function() {
this.process();
this.total = this.val1 + this.val2;
this.stack.push(this.total);
}
this.minus = function() {
this.process();
this.total = this.val2 - this.val1;
this.stack.push(this.total);
}
}
如何让 RPNCalculator 对象继承数组方法,而不自己创建 push 和 pop 方法? 例如,如果我执行以下操作
rpnCalculator = new RPNCalculator();
rpnCalculator.push(2);
它会将数字 2 添加到堆栈数组中
【问题讨论】:
-
最好不要使用
.stack属性,而是使用RPNCalculator类数组实例。
标签: javascript arrays object prototype