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 添加到堆栈数组
最佳答案
如果您想要 Array
提供的所有方法,可以从使用 Object.create
从 Array
继承原型(prototype)开始然后将自定义函数添加到新的构造函数原型(prototype)中。
var Foo = function () {};
Foo.prototype = Object.create(Array.prototype);
Foo.prototype.process = function process() {
// `this` is the array
// Do some logic...
// returning `this` to show it is the array
return this;
}
var foo = new Foo();
foo.push(3);
foo.push(2);
foo.push(1);
document.write(
'<h3>foo</h3>' +
'<pre>' + JSON.stringify(foo, null, 4) + '</pre>' +
'<h3>foo.process()</h3>' +
'<pre>' + JSON.stringify(foo.process(), null, 4) + '</pre>'
);
关于Javascript:让对象继承数组方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31127678/