Alex
Alex

Reputation: 2196

How do I use prototype?

I am trying to learn how to use prototype in javascript, and I was hoping someone could explain the following to me.

Lets say I have a object with a prototype looking like this:

function Calc(sumOne, sumTwo) {
    this.sumOne = sumOne;
    this.sumTwo = sumTwo;
}

Calc.prototype.add = function() {
    var sum = this.sumOne + this.sumTwo;
    return sum;
}

Then lets say these objects are stored in an array when they where created like this.

var numbers = [];

numbers.push(new Calc(1, 2));
numbers.push(new Calc(3, 4));
numbers.push(new Calc(5, 6));

This would result in an array looking something like this

numbers = [{sumOne: 1, sumTwo: 2}, {sumOne: 3, sumTwo: 4}, {sumOne: 5, sumTwo: 6}];

If I now would like to run the prototype on these objects to get the result (3, 7 and 11). How would I do this?

Upvotes: 0

Views: 51

Answers (2)

arcyqwerty
arcyqwerty

Reputation: 10675

For each Calc instance in the array, call .add() on it.

numbers.map(function(calc) {
  return calc.add();
});

Upvotes: 1

AmmarCSE
AmmarCSE

Reputation: 30557

Iterate over them and call the prototype method

function Calc(sumOne, sumTwo) {
  this.sumOne = sumOne;
  this.sumTwo = sumTwo;
}

Calc.prototype.add = function() {
  var sum = this.sumOne + this.sumTwo;
  return sum;
}


var numbers = [];

numbers.push(new Calc(1, 2));
numbers.push(new Calc(3, 4));
numbers.push(new Calc(5, 6));


numbers.forEach(function(calcObject, index) {
  numbers[index] = calcObject.add();

});
console.log(numbers)

Upvotes: 0

Related Questions