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 = [];
}
};
You are most likely trying to access the (new) prototype object before it is assigned. You are allowed to use the
Calculator
constructor because function declarations are subject to hoisting. Assignments are not.The prototype of objects you construct before making those changes will be the object that is the prototype at the time of the call.
Note that you can use prototype properties with an object that was created prior to them being added to the prototype, if the prototype object itself was not changed, but merely extended.
It is only important that you don't make the calls before the functions are assigned.