如何从一个javascript文件获取原型方法的价值到另一个javascript文件的原型方法?

时间:2017-10-19 05:35:40

标签: javascript jasmine

我正在学习Javascript并使用Jasmine进行测试。我有2个文件。文件有更多细节。这个特殊部分不起作用。当我运行测试时,它没有说“预期NAN等于10”。我想从Counter.js获取totalCount来计算MyProject.js,然后将其除以迭代。任何人都可以帮我这个吗?

Counter.js

function Counter(){
this.count = 0;
}
Counter.prototype.startCount = function(count){
this.count += count;
};
Counter.prototype.totalCount = function(){
return this.count;
}

MyProject.js

function MyProject() {
this.iteration = 0;
}
MyProject.prototype.addIteration = function(iteration) {
this.iteration += iteration;
}
MyProject.prototype.calculate = function() {
var averageCount = Counter.prototype.totalCount();
return averageCount/this.iteration;
}

MyProject_spec.js

describe("MyProject", function() {
var project, iteration1, iteration2, iteration3;
beforeEach(function(){
project = new MyProject();
iteration1 = new Counter();
iteration1.startCount(10);

iteration2 = new Counter();
iteration2.startCount(20);

iteration3 = new Counter();
iteration3.startCount(10);
});
it("can calculate(the average number of counting completed) for a set of iterations", function(){
project.addIteration(iteration1);
expect(project.calculate()).toEqual(10);
});

1 个答案:

答案 0 :(得分:0)

  

当我进行测试时,它未能说"预期NAN等于10"

您的问题是addIteration期待数字作为参数,并且您将Counter传递给相同的人。

project.addIteration(iteration1);

您需要以

的方式修改MyProject
function MyProject() 
{ 
    this.allIteration = [];
    this.totalIterationCount = 0;
}
MyProject.prototype.addIteration = function(iteration) 
{
    this.allIteration.push( iteration ); 
    this.totalIterationCount += iteration.totalCount(); 
}
MyProject.prototype.calculate = function() 
{
    return this.totalIterationCount /this.allIteration.length;
}

<强>演示

&#13;
&#13;
function Counter() {
  this.count = 0;
}
Counter.prototype.startCount = function(count) {
  this.count += count;
};
Counter.prototype.totalCount = function() {
  return this.count;
}

function MyProject() {
  this.allIteration = [];
  this.totalIterationCount = 0;
}
MyProject.prototype.addIteration = function(iteration) {
  this.allIteration.push(iteration);
  this.totalIterationCount += iteration.totalCount();
}
MyProject.prototype.calculate = function() {
  return this.totalIterationCount / this.allIteration.length;
}

project = new MyProject();
iteration1 = new Counter();
iteration1.startCount(10);
iteration2 = new Counter();
iteration2.startCount(20);
iteration3 = new Counter();
iteration3.startCount(10);
project.addIteration(iteration1);
console.log(project.calculate());
project.addIteration(iteration2);
console.log(project.calculate());
project.addIteration(iteration3);
console.log(project.calculate());
&#13;
&#13;
&#13;