gremo
gremo

Reputation: 48899

Why this JavaScript is not dynamically creating object properties?

This code can't dynamically set object properties. console.log(key, val) shows that the loop iterates correctly over the options (merged with defaults and filtered by the keys of defaults):

function Foo(options) {
   var defaults = { foo: "bar" },
       options  = _.defaults(options || {}, defaults);

    _.each(_.pick(options, _.keys(defaults)), function(val, key) {
        this[key] = val; // Not working
    });

    this.baz = 'bar'; // Works
};

var foo = new Foo();

foo.hasOwnProperty('foo'); // false
foo.hasOwnProperty('baz'); // true

Q1: Why it's not working? Is this[key] wrong?

Q2: How (normally) one should deal with the key-sensitive problem, that is passing{"FOO": "bar"}?

Functions (if matters): ._defaults, _.pick and _.keys.

Upvotes: 0

Views: 50

Answers (2)

Roger C
Roger C

Reputation: 305

Every function has its own "this", so the "this" inside the _.each isn't the same that is in Foo. You need to manually pass the "this" from Foo to the each, in order to do that, you can use the underscore function _.bind.

Upvotes: 0

jevakallio
jevakallio

Reputation: 35890

The this context in the each callback is not pointing to the containing function Foo. You can provide the context as the second argument to each:

_.each(_.pick(options, _.keys(defaults)), function(val, key) {
    this[key] = val;
}, this);

Note that you don't need to iterate over the values at all, you can just use _.extend:

_.extend(this, _.pick(options, _.keys(defaults)));

Upvotes: 4

Related Questions