0

Lets say I have a javascript object with the the following

var Settings = function () {        
    this.timelimit = 0;
    this.locked    = false;     
    this.expires   = null;      
    this.age       = null;      
};

And then I set some get/set functions like:

Settings.prototype = {

        getAllAges: function () {
            return self.age;
        },

        getTimeLimit: function () {
            return self.timelimit;
        },
        load: function() {
           data_from_local_storage = LoadLocalStorage();
        }
 }

In data_from_local_storage I have JSON variables that match the above variables (timelimit, locked etc .. )

Issue is, the object var settings_ref = Settings() have all these 4 variables - but also have these 3 functions assigned in settings_ref - due to this OO behavior I need to write inside the load() function:

this.timelimit = data_from_local_storage.timelimit
this.age       = data_from_local_storage.age
this.locked    = data_from_local_storage.locked

Because if I'll write this = data_from_local_storage it will destroy my object.

So how can I avoid writing all these variables one-by-one ?

  • w/o a for loop inside a function
  • in this example are just 4 but there are much much more and I cannot write it everywhere everytime
  • I'm looking for some .update() function like in Python or something ..

Any quick shortcut that someone know ?

4
  • 2
    Those references to self should be this. Commented Oct 17, 2016 at 13:44
  • stackoverflow.com/questions/11197247/… might help Commented Oct 17, 2016 at 13:45
  • Place all your options inside an another object literal, eg. this.options = {timelimit:0,...}, and then you can replace the options very simply by doing this.options = data_from_local_storage.. This of course then makes putting options into local storage just as easy.. :) Commented Oct 17, 2016 at 13:50
  • @Pointy sorry I wrote a quick code, but I usually write var self = this so that it won't be confuse within other functions there .. Commented Oct 17, 2016 at 13:57

2 Answers 2

2

You can use Object.assign() in ES2015:

    load: function() {
       Object.assign(this, LoadLocalStorage());
    }

It's apparently not supported yet in IE, but there's a polyfill on the MDN page:

if (typeof Object.assign != 'function') {
  (function () {
    Object.assign = function (target) {
      'use strict';
      // We must check against these specific cases.
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert undefined or null to object');
      }

      var output = Object(target);
      for (var index = 1; index < arguments.length; index++) {
        var source = arguments[index];
        if (source !== undefined && source !== null) {
          for (var nextKey in source) {
            if (source.hasOwnProperty(nextKey)) {
              output[nextKey] = source[nextKey];
            }
          }
        }
      }
      return output;
    };
  })();
}

(Personally I would use Object.defineProperty() to add the method, but that's verbatim from MDN.)

(edit though I guess if you don't have Object.assign() you may not have Object.defineProperty() either :)

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

1 Comment

Object.assign was exactly what I was looking for - thanks !
1

If you store the data inside another object literal, it makes persisting things to localstorage and back a lot easier.. Here is an example..

//pretend local storage loader
function LoadLocalStorage() {
  return {
      timelimit: 100,
      locked: true,
      expires: new Date(),      
      age:40
  }
}

var Settings = function () {        
    this.data = {
      timelimit: 0,
      locked: false,
      expires: null,      
      age:null
    }
};

Settings.prototype = {
   getAllAges: function () {
     return this.data.age;
   },
   getTimeLimit: function () {
     return this.data.timelimit;
   },
   load: function() {
     this.data = LoadLocalStorage();
   }
}

var settings = new Settings;
console.log('Age before our load');
console.log(settings.getAllAges());
settings.load();
console.log('Age after our load');
console.log(settings.getAllAges());

3 Comments

You might wish to correct as var settings = new Settings();
@Redu Apparently there optional. stackoverflow.com/questions/3034941/…
it's also an option, I just want the this.variable just like any other native object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.