【问题标题】:Javascript: make an object inherit array methodsJavascript:使对象继承数组方法
【发布时间】: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


【解决方案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>'
);

【讨论】:

  • 感谢您的建议!我会尽力从这些中学习。
【解决方案2】:

你可以这样做:

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

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

【讨论】:

  • 谢谢。我的印象是有一种方法可以使用原型定义对象,以便它可以继承所有数组方法。涉及下划线underscorePROTOunderscoreunderscore 的东西。我对此很陌生,所以如果我没有多大意义,我深表歉意。
  • 查看杰森的回答
  • 您定义的问题不需要原型继承来解决它。既然你只需要两个方法,为什么要引入 Array.protype 所拥有的所有东西呢?
  • 你说得对,我不需要继承所有的Array属性。您的回答非常有帮助,这是我不知道的一种技术。我只是想,当我在这里时,我可以获得与该主题相关的更多信息。
猜你喜欢
  • 1970-01-01
  • 2023-04-11
  • 2019-01-30
  • 1970-01-01
  • 2014-01-09
  • 2015-02-07
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
相关资源
最近更新 更多