Javascript:使对象继承数组方法

时间:2015-06-30 00:29:48

标签: javascript arrays object prototype

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);  
    }
}

如何在不创建push和pop方法的情况下使RPNCalculator对象继承数组方法? 例如,如果我执行以下操作

rpnCalculator = new RPNCalculator();
rpnCalculator.push(2);

它会将数字2添加到堆栈数组

2 个答案:

答案 0 :(得分:1)

你可以这样做:

this.push = this.stack.push.bind(this.stack); this.pop = this.stack.pop.bind(this.stack);

这只会使用stack的方法,而不是定义自己的方法。

答案 1 :(得分:1)

如果您希望Array提供的所有方法可能首先使用Object.createArray继承原型,然后将自定义函数添加到新构造函数原型中。



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>'
);
&#13;
&#13;
&#13;