-1

When you try to stringify any object, you only get like a json the public properties but, if my object have private properties, how I can save it?

Daniel
  • 61
  • 1
  • 9

3 Answers3

4

Here is an example with a constructor for a Person object. In this case, We override the toJSON method of this object to include the private variable "age". The toJSON method is used internally by JSON.stringify

function Person(name, age) {
    var age = age  // Only accessible in the scope on the constructor
    this.name = name

    this.toJSON = function() {
        return {age: age, name: this.name}
    }
}

// eg with localStorage
var john = new Person('John', 40)
localStorage.setItem('John', JSON.stringify(john))

I must add as commented previously that there is no such thing as a private property in javascript : only scoped variables and closures as getter/setter to make them accessible to the outside

matsurena
  • 71
  • 4
  • Please at least say what your code does. Don't just throw code. – Adrian Dec 31 '17 at 03:44
  • I think its worth noting that once the object is pulled out of local storage, the private members are no longer private. Nothing can be done about this, as far as I know. Still, this is the best answer at this time. –  Dec 31 '17 at 04:24
2

Currently, there are no such things as private members (properties, methods) on Javascript objects. An ECMAScript proposal will bring private fields to a future version of Javascript. However, those private fields will be strictly accessible from within the scope of the object. It will be impossible to access them from outside the scope of the object, or even know about their presence.

If you are defining your own objects, create a toJSON() method and return the string representation of the object however you wish.

Arash Motamedi
  • 9,284
  • 5
  • 34
  • 43
-1

All javaScript properties are public; local storage stores key:value pairs that are only retrievable by the domain that has stored them, that is if cookies are enabled! It sounds like from the question you are trying to find out a way to have persistent data storage on a "client side" scripting language, the answer is there is no guarantee of persistent data existing on a client machine without other technologies, for system security; access to a client machine's storage system is severely restricted. Local Storage is only able to store a limited amount of data that is restricted by the browser and operating system that owns it.

  • "on a "client side" scripting language" You mean the language the question is tagged with: JavaScript? –  Dec 31 '17 at 03:49
  • Yes, it is a client side scripting language unless you are using node.js! I put it in quotes to emphasize the fact that it is a client side scripting language. – Matthew Lagerwey Dec 31 '17 at 04:08