Question

Below is the Javascript object that I have:

var calc = {
    title : 'Calculator',
    plus : function( a, b ) {
        return (
           console.log(this),    // calc
           console.log(arguments), // [ 3, 5 ]
           console.log(a+b), // 8
           console.log(this.title) // Calculator
        )
    }
};

And I am trying to access the prototype of this object calc by the following:

calc.prototype.getNum = function( numStr ) {
  return isNaN(parseInt(numStr)) ? 'Not a valid number!' : parseInt(numStr);
};

But it keeps giving the following error, whenever I execute it!

TypeError: Cannot set property 'getNum' of undefined

Can anyone please tell me what I'm doing wrong here?

Was it helpful?

Solution

prototype is a property of functions. It will not be available on object literals. So, you might want to convert the calc to a function, like this

function calc() {
    this.title = 'Calculator';
}

calc.prototype.plus = function( a, b ) {
  console.log(this);
  console.log(arguments);
  console.log(a+b);
  console.log(this.title);
}

Now, you should be able to add the getNum to the prototype of calc.

OTHER TIPS

Use calc.constructor.prototype

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top