简体   繁体   中英

JavaScript TypeError, Cannot read property of undefined, but the function is defined. What am I doing wrong?

I keep getting the error: "TypeError: Cannot read property 'push' of undefined"

The error is in this line: "this.courseName.push(dish);"

Here is the code:

let menu = {
    _courses: {
      _appetizers:[] ,
      _mains:[],
      _desserts: []
    },

    addDishToCourse(courseName, dishName, dishPrice){
        const dish = { name: this.dishName, price: this.dishPrice };

        // ERROR HERE: **this._courses[courseName].push(dish);**
    },
};

I have been stuck with this error for hours. Is there something I'm not seeing?

Sorry if there is a simple solution to this. I'm relatively new to JavaScript.

Edit:

I was indeed calling the key incorrectly. I am now calling the function as:

  menu.addDishToCourse("_appetizers", "random", 10);
  console.log(menu._courses._appetizers);

When I log this in compiler it returns:

    [ { name: undefined, price: undefined } ]

It seems like the function isn't getting called. Am I approaching this fundamentally incorrectly?

It is the scope that is the issue.

this is the object itself (the menu in this case) and has _courses and addDishToCourse as its properties.

Inside the addDishToCourse this is looking at the object for the dishName and dishPrice , but they are scoped to the function itself (from the parameters).

So the correct code would be like so:

let menu = {
        _courses: {
            _appetizers: [],
            _mains: [],
            _desserts:[]
        },

        addDishToCourse(courseName, dishName, dishPrice) {
            const dish = { name: dishName, price: dishPrice };

            this._courses[courseName].push(dish);
        }
    }    

menu.addDish("_mains", "Pizza", "10");

Your first problem is that you were passing a wrong courseName to the function, that's why you get the error.

And your second problem is that you are assigning wrong values, to object to push in your courses array when you used { name: this.dishName, price: this.dishPrice } .

In fact when you use this.dishName you were trying to get dishName from your menu object that's why it's undefined , you just need to use the parameters dishName and dishPrice you are passing arguments to the function.

    const dish = {
      name: dishName,
      price: dishPrice
    };

    this._courses[courseName].push(dish);

This is a working Demo:

 let menu = { _courses: { _appetizers: [], _mains: [], _desserts: [] }, addDishToCourse(courseName, dishName, dishPrice) { const dish = { name: dishName, price: dishPrice }; this._courses[courseName].push(dish); }, }; menu.addDishToCourse("_appetizers", "random", 10); console.log(menu._courses._appetizers); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM