Question

I got the next code with some getters and setters done this way so I can hide the parameters.

// trackedWebsite: does not use the new to create the object trackedWebsite. 
//Creates an object with private parameters only accessible by the getter 

var trackedWebsite = function(url,extensions){
return {
        //This returns the URL of the website
        get get_URL() {
            return url;
        },

        get get_Extensions(){
            return extensions;
        },

        set set_Extensions(ext){
            this.extensions = ext;
        }


    }

}

At some point, I want to save the information an array of trackedWebsite called websites in localStorage, so I parse it with JSON:

localStorage.websites=JSON.stringify(websites);

Finally at some point I load all the websites again:

function getAllWebsites(){
if (localStorage.websites === undefined){
    return new Array();
}
return JSON.parse(localStorage.websites);

}

When I do this, the get functions work properly, but I find that the trackedWebsites in the array i receive back does not include the setter. When I try to use it, I get: Uncaught TypeError: Object # has no method 'set_Extensions' . Why does this happen? Why does the getter works properly but not the setter?

EDIT: Added the code where the setter is invoked

            websites[index].set_Extensions(extensions);

Thank you

Was it helpful?

Solution

It's not just your setter that's broken, but also your getter. After serializing your object to a JSON string, the result is something like

{"get_URL":"http://....","get_Extensions":["extension1","extension2"]}

If you really want to reconstruct the original object, use

function getAllWebsites() {
    if (localStorage.websites === undefined){
        return [];
    }
    var parsedJSON = JSON.parse(localStorage.websites);
    // Assume that parsedJSON is an array
    return parsedJSON.map(function(website) {
        return trackedWebsite(website.get_URL, website.get_Extensions);
    });
}

You can define a custom JSON serialization and parsing method if you need more flexibility - see JSON.stringify and JSON.parse.


There's another issue with your code. It's not idiomatic, because your getters/setters are prefixed with set_ and get_. Your "trackedWebsite" object works as follows, at the moment:

var url = website.get_URL;
website.set_Extensions = ...;
var extensions = website.get_Extensions;

This should actually be

var url = website.URL;               // Being at the right side implies getter
website.extensions = ...;            // Assignment implies setter
var extensions = website.extensions; // Being at the right side implies getter

Or at the very least:

var url = website.get_URL();
website.set_Extensions(...);
var extensions = website.get_Extensions();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top