Silver Challenge - Do I have the right solution?

  function DataStore() { // our function of DataStore
// making data private through closure
this.data = function(){
  return {};
};
}  

Got my solution reading through MDN doc.

Challenge: Update your DataStore module so that the data property is private to the module.

Also need help understanding the questions asked… I have attempted some answers.

Are there any reasons you would not want to do this?

  • To leave the property public, so its information can be accessed without getters and setters.

What happens if you declare multiple instances of DataStore?

  • Tested multiple instances on private and public properties , but couldn’t find a difference. Did I miss something?

Thanks for sharing the link. Based on this challenge following the “For the More Curious: Private Module Data”, I think the idea is to put the line

var data = {};

inside the IIFE defined in datastore.js but not inside the DataStore() function. However, I think from that point forward, you would need to not refer to this in the methods that are added.

As for why you wouldn’t want to do this, I would say that then each DataStore object would have the same data object. We want each truck to have a different DataStore object. But the primary use of a DataStore object is its data property. So we wouldn’t achieve our goal if we make data private.

Hopefully somebody else will chime in if I am wrong.

You are right @ballgeier

You need to declare var data = {}; at the root of the IIFE as you said.

Furthermore, from now on you need to refer to data without this.

The problem with this approach, as you said, is that all DataStore instances will share the same data object, which is really bad.

That said, there is one way to have private fields without sharing the data object among all the instances: simply put all the functions inside the constructor, like this:

function DataStore() {
  var data = {};
  this.add = function (key, val) {
    data[key] = val;
  };
  this.getAll = function () {
    return data;
  };
}

Note that to make data private you declare it with var.

This link is interesting: http://www.crockford.com/javascript/private.html

albertvila, can you explain more about instances sharing the same object?

@incubusj
Here’s what i found on stackoverflow:

Methods defined inside the constructor have access to private variables because all functions have access to the scope in which they were defined.

Methods defined on a prototype are not defined within the scope of the constructor, and will not have access to the constructor’s local variables.

You can still have private variables, but if you want methods defined on the prototype to have access to them, you should define getters and setters on the this object, which the prototype methods (along with everything else) will have access to.