2015-06-30 22 views
1
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对象继承数组方法,而无需自己创建推送和弹出方法? 例如,如果我这样做Javascript:使一个对象继承数组方法

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

会2号添加到堆叠阵列

+0

你最好的选择是不使用'.stack'财产,而是让'RPNCalculator'例如阵列等。 – Bergi

回答

1

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

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

+0

感谢您的建议!我会尽我所能从这些中吸取教训。 –

1

你可以这样做:

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

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

+0

谢谢。我的印象是有一种使用原型来定义对象的方法,以便它可以继承所有的数组方法。一些涉及下层防御核心议员反对的内容。我对此很新,所以如果我没有太大意义,我表示歉意。 –

+1

查看Jason的回答 – Jan

+0

您定义的问题不需要原型继承来解决它。既然你只需要两种方法,为什么还要引入Array.protype的其他东西? – TheDude