在Javascript中创建科学计算器

时间:2016-02-16 21:44:31

标签: javascript

我有一个科学计算器,我有一个计算器。我的问题是如何编写符合此规范的科学计算器类。

describe( "ScientificCalculator", function(){
 var calculator;
 beforeEach( function(){
 calculator = new ScientificCalculator();
 } 
);

it( "extends Calculator", function(){
 expect( calculator ).to.be.instanceOf( Calculator );
 expect( calculator ).to.be.instanceOf( ScientificCalculator );
 } 
);

it( "returns the sine of PI / 2", function(){
 expect( calculator.sin( Math.PI / 2 ) ).to.equal( 1 );
 } 
);

it( "returns the cosine of PI", function(){
 expect( calculator.cos( Math.PI ) ).to.equal( -1 );
 } 
);

it( "returns the tangent of 0", function(){
 expect( calculator.tan( 0 ) ).to.equal( 0 );
 } 
);

it( "returns the logarithm of 1", function(){
 expect( calculator.log( 1 ) ).to.equal( 0 );
 } 
);
} 
);

2 个答案:

答案 0 :(得分:1)

似乎是标准JavaScript inheritance。 您可以使用类似于下面的内容来达到预期效果。 每个OP的新数据编辑代码。

//Define a calculator base class
var Calculator = function(op1, op2) { 
  this.add = function(op1, op2) { return op1 + op2; }; 
  this.multiply = function(op1, op2) { return op2 * op1; }; 
  this.subtract = function(op1, op2) { return op1 - op2; }; 
  this.divide = function(op1, op2) { 
    if (op1/op2 === Infinity) {
      return Infinity - Infinity; 
    } else return op1/op2; 
  }; 
};


//define a sub class scientific calculator
function ScientificCalculator() {}
ScientificCalculator.prototype = new Calculator();
ScientificCalculator.prototype.constructor = Calculator;
//Add methods to the base class
ScientificCalculator.prototype.sin = function() {
  //Your imlementation here for Sin, repeat same for cos and others
};
var sc = new ScientificCalculator();

答案 1 :(得分:0)

假设您已经在某处定义了Calculator类,您可以尝试这样的事情:

function ScientificCalculator() {
  // whatever you want, private variable declarations perhaps?
}

ScientificCalculator.prototype = Object.create(Calculator.prototype);
ScientificCalculator.prototype.constructor = Calculator;

ScientificCalculator.prototype.sin = function(x) {
  return Math.sin(x);
}

ScientificCalculator.prototype.cos = function(x) {
  return Math.cos(x);
}

ScientificCalculator.prototype.tan = function(x) {
  return Math.tan(x);
}

ScientificCalculator.prototype.log = function(x) {
  return Math.log(x);
}