2015-06-30 24 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