Javascript:让对象继承数组方法

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

如何让 RPNCalculator 对象继承数组方法,而不需要自己创建 push 和 pop 方法? 例如,如果我执行以下操作

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

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

最佳答案

如果您想要 Array 提供的所有方法,可以从使用 Object.createArray 继承原型(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/

相关文章:

java - 链接列表对象不存储字符串输入,这会导致链接列表为空

javascript - 无法以编程方式使用 Javascript 填充 iframe

javascript - 模板项目中现有的模板组件

powershell - 创建自定义 Powershell 对象的多个实例

javascript - 对象的克隆继承对第一个对象所做的 future 更改

javascript - cssRules 无法读取多个样式表类属性值

Javascript - Safari 中是否有 element.scroll 或 element.scrollTo 的替代方案?

javascript - 如何在异步nodejs中完成所有过程并打印出消息?

php - 如何在 php 上从数据库创建类别路径

javascript - 过滤动态数组值