0

I'm trying to create a class method but I don't see what I am doing wrong here. Here is my code

var Invoice = function(title) {
this.title = title;

this.addItem = function addItem(item_name) {
  console.log("Hello, you added " + item_name);
};

invoice = new Invoice("Video games")
invoice.addItem('Xbox 360');

I get the following error:

TypeError at line undefined: invoice.addItem is not a function
Jaime Rios
  • 1,956
  • 2
  • 15
  • 20
  • `function addItem` should be `function ` – Mahi Nov 30 '16 at 18:55
  • 4
    @Mahi: That doesn't actually matter. It's valid to give a function expression a name. –  Nov 30 '16 at 18:56
  • 3
    Jamie: You posted an invalid code snippet because you're missing a `}` somewhere, so it won't run at all. If the closing `}` is *before* the `this.addItem = function...`, then that's your issue. –  Nov 30 '16 at 18:56
  • It is working. Could you copy & paste the code in console and run(after closing bracket in the function )? – maheshiv Nov 30 '16 at 18:59
  • 1
    Try Invoice.prototype.addItem = function(item_name){here your code} and add missed }. – rad11 Nov 30 '16 at 18:59
  • What do you get if you run `console.log(invoice)`? – rabbitco Nov 30 '16 at 19:01

1 Answers1

3

Simple typo, which goes to show why proper indentation is ESSENTIAL:

var Invoice = function(title) {
    this.title = title;
    this.addItem = function addItem(item_name) {
         console.log("Hello, you added " + item_name);
    };
};  //you were not closing your constructor

You could, and probably should use prototype.

var Invoice = function(title) {
    this.title = title;
};
Invoice.prototype.addItem = function(item_name){
     console.log("Hello, you added " + item_name);
};

For a detailed explanation of the difference, see JS - why use prototype

or in ES6, with a class :

class Invoice {
     constructor(title){
         this.title = title;
     }
     addItem(item_name) {
          console.log("Hello, you added " + item_name);
     }
}

And in case your invoice is a node module, and your question is made of concatenated code, don't forget to add :

module.exports = Invoice;

So you can require it anywhere.

In all those cases, invocation is done in the same way :

let invoice = new Invoice("Video games") //or var if ES5
invoice.addItem('Xbox 360');
Community
  • 1
  • 1
xShirase
  • 11,975
  • 4
  • 53
  • 85