1

My object class:

 class Dog {

        constructor(name) {

            var _name;

            _name = name;

            this.getName = function () {
                return _name;
            }
        }
    }

I have a button on click event wire to the following function:

            document.getElementById("btnTest").onclick = function () {

            var animals = [];

            var name = document.getElementById("name").value;
            var bday = document.getElementById("bday").value;
            var age = document.getElementById("age").value;
            var desc = document.getElementById("description").value;

            animals.push(new Dog(name, bday, age, desc));

            var serializedAnimals = JSON.stringify(animals);

            window.localStorage.setItem("list",serializedAnimals);

            var list = JSON.parse(window.localStorage.getItem("list"));

            console.log(list.getName());
        }

However when i trigger the function from the button click I get this error console message box:

TypeError: list.getName is not a function

What am I doing wrong?

2
  • Another helpful duplicate: stackoverflow.com/questions/40201589/… Commented Mar 22, 2019 at 3:43
  • Use instead localStorage.setItem("list",serializedAnimals); var item = localStorage.getItem('list'); console.log(item) Commented Mar 22, 2019 at 3:46

1 Answer 1

0

Methods do not get serialised by JSON.stringify

class Dog {

      constructor(name) {

          var _name;

          _name = name;

          this.getName = function () {
              return _name;
          }
      }
  }

var animals = [];

animals.push(new Dog('name', 'bday', 'age', 'desc'));

var serializedAnimals = JSON.stringify(animals);

console.log(serializedAnimals);

console.log(JSON.stringify({ func: () => {} }));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.