I am trying to understand Javascript's prototype. I know I can add functions to prototype individually Calculator.prototype.calculate = function(){};
, however when I tried setting a new prototype everything fell apart. calc.prototype returns undefined. My question is why can't we set a new Object as the prototype? How to add methods to prototype in bulk instead of adding it one by one ?
var calc = new Calculator();
function Calculator(){
this.array = [];
this.results = 0;
}
Calculator.prototype = {
calculate: function(){
try{
results = eval(this.array.join(''));
this.array = [results];
return results;
}
catch(error){
alert('Wrong arguments provided');
return this.array.join('');
}
},
isNumber: function(str){
return !isNaN(parseFloat(str)) && isFinite(str);
},
addToOperationsArray: function(str){
if (this.array.length <= 0 && !this.isNumber(str)){ // Don't add operand before any number.
return;
}
this.array.push(str);
},
clearEverything: function(){
this.array = [];
}
};