0

此代码无法动态设置对象属性。 console.log(key, val)表明循环正确地迭代了options(与 的键合并defaults和过滤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:为什么它不起作用?this[key]错了吗?

Q2:(通常)应该如何处理按键敏感问题,即通过{"FOO": "bar"}

功能(如果重要)._defaults_.pick_.keys

4

2 回答 2

4

回调中的this上下文each未指向包含函数Foo。您可以将上下文作为第二个参数提供给each

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

请注意,您根本不需要迭代这些值,您可以使用_.extend

_.extend(this, _.pick(options, _.keys(defaults)));
于 2013-02-08T16:05:20.513 回答
0

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.

于 2013-02-08T16:06:16.660 回答