How can I * unzip * an object into a function area?

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 .

While this decompresses the variables from the object, it sets them to the global scope (bound to window ), because this is window in this case.

So, after the function, I can do alert(abc) , and it will warn def , which is bad.

How can I set the scope of variables for this function?

+4
source share
2 answers

If you want to put the properties of an object in the scope of a function, you can expand the scope with with :

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

Disclaimer : Make sure you read the documentation and the flaws with . It should be avoided and also deprecated:

Using with not recommended and is prohibited in ECMAScript 5 strict mode. The recommended alternative is to assign an object whose properties you want to get into a temporary variable.

So why not get up with options ?

+2
source

You can access the function from the inside 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); 
+2
source

Source: https://habr.com/ru/post/1345477/


All Articles