0

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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Kamran Ahmed
  • 11,809
  • 23
  • 69
  • 101
  • Why do you want to add something to the prototype, if you have only one "instance" of your object literal? – Bergi Mar 15 '14 at 12:33
  • @Bergi because that's what you do, when you are learning something... – Kamran Ahmed Mar 15 '14 at 13:40
  • @Bergi BTW, is that a valid reason to downvote? – Kamran Ahmed Mar 15 '14 at 13:41
  • No, I didn't downvote. – Bergi Mar 15 '14 at 13:48
  • If there is ever going to be only one calc then you can leave it as object literal, put all functions in the body of that and forget about prototype. If you're planning to create several calc instances then you may use prototype. For an explanation about prototype and constructor functions you can read this answer: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Mar 15 '14 at 13:53
  • possible duplicate of [How does JavaScript .prototype work?](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work) – Bergi Mar 15 '14 at 13:54

2 Answers2

0

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
-1

Use calc.constructor.prototype

Paul Kotets
  • 199
  • 5