How to set a function's prototype

286 Views Asked by At

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 = [];
    }
};
1

There are 1 best solutions below

0
On BEST ANSWER

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.

// use the default prototype
var test1 = new Test();

// a new prototype is assigned
// objects created from this point will use it
Test.prototype = {
  report: function(){ alert('jah live children yea'); }
};
var test2 = new Test();

test1.report();     // Uncaught TypeError: test1.report is not a function
test2.report();     // alerts


function Test(){}   // hoisted so you can use it before this line

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.

var test1 = new Test();

test1.report();     // Uncaught TypeError: test1.report is not a function

// extend the prototype object
// the added property is accessible by existing objects
Test.prototype.report = function(){
  alert('jah live children yea');
};

test1.report();     // alerts


function Test(){}