1

I would like to set a variable with the following function setDef().

My example do not work. What I have to do?

    var defs = {
      title: document.title,
      action:   "pageview"
    };

    var setDefs = function(a,b) {
       defs.a= b;     // this: defs.title = b; is working.
    };

    setDefs("title","test");
hamburger
  • 1,339
  • 4
  • 20
  • 41

1 Answers1

3

Use bracket notation, object[variable], instead:

var setDefs = function(a,b) {
       defs[a] = b;
};

Also it would be better suited to include this method in the object:

var defs = {
      title: document.title,
      action:   "pageview",
      setDefs: function(a,b) {
       this[a] = b; 
      }
};

defs.setDefs("title","test");

// > defs
// Object {title: "test", action: "pageview", setDefs: function}
agconti
  • 17,780
  • 15
  • 80
  • 114
  • thx for your hint, good idea. but if I include it, I can't change an exsisting variabale. – hamburger Aug 14 '14 at 16:54
  • @hamburger, what do you mean? with your original code it can only add properties to the defs object. – agconti Aug 14 '14 at 16:57
  • setDefs("title","test"); will overwrite the origin property of the defs object. But if I think about your proposal to include setDefs in the object, it will do the same. – hamburger Aug 14 '14 at 17:06