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?

John Vuong
  • 21
  • 5
  • Another helpful duplicate: https://stackoverflow.com/questions/40201589/serializing-an-es6-class-object-as-json – Robby Cornelissen Mar 22 '19 at 03:43
  • Use instead `localStorage.setItem("list",serializedAnimals); var item = localStorage.getItem('list'); console.log(item)` – ABC Mar 22 '19 at 03:46

1 Answers1

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: () => {} }));
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60