How can I *unpack* an object into a function's scope?

心不动则不痛 提交于 2019-12-19 20:38:13

问题


I have this code...

function a(options) {
    for (var item in options) {
       if ( ! options.hasOwnProperty(item)) {
          continue;
       }
       this[item] = options[item];
    }
}

a({ 'abc': 'def' });

jsFiddle.

Whilst this unpacks variables from the object, it sets them to global scope (attached to window) because this is window in that circumstance.

So after the function I can do alert(abc) and it will alert def, which isn't good.

How would I set the scope of the variables to the function?


回答1:


If you want to put the properties of the object in the scope of the function, you can extend the scope by using with:

function a(options) {
    with(options) {
        // properties of `options` are in the scope
        alert(abc);
    }
}

Disclaimer: Make sure you read the documentation and about disadvantages of with. It should be avoided and is also kind of deprecated:

Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.

So the questions is why not stick with options ?




回答2:


You can access the function from inside itself using the callee property:

function a(options) {
    var thiz = arguments.callee;
    for (var item in options) {
        if (!options.hasOwnProperty(item)) {
            continue;
        }
        thiz[item] = options[item];
    }
}

a({
    'abc': 'def'
});

alert(a.abc);

Alternatively, you can set the scope when you call it:

function a(options) {
    for (var item in options) {
        if (!options.hasOwnProperty(item)) {
            continue;
        }
        this[item] = options[item];
    }
}

a.call(a, {
    'abc': 'def'
});
alert(a.abc);


来源:https://stackoverflow.com/questions/5453636/how-can-i-unpack-an-object-into-a-functions-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!