📜 ⬆️ ⬇️

Visibility blocking emulation with with in javascript


For finding a good photo, thanks to ant99 and also to the photographer.
Some time ago I wrote about how to block visibility in JavaScript using the let construct. As it turned out from the comments, let (like JavaScript 1.7-1.8.5) is supported only by monkeys and Rhino-based browsers. I was disappointed, but 15 minutes ago I thought up (although it was said loudly, probably, someone had already thought up before me) a crutch for a not so beautiful, but nevertheless working code. He uses the with construction (yes, I know that it is counted among the Bad Parts because of the uselessness and inefficiency, but right now I will refute the first statement).



I will consider a simple example.
With the let construct, it looks like this:
foo = 10; bar = 20; let(foo=20,bar=10){ console.log(foo,bar); //20 10 } console.log(foo,bar); //10 20 

')
And using with:
 foo = 10; bar = 20; with({ foo:20, bar:10 }){ console.log(foo,bar); //20 10 } console.log(foo,bar); //10 20 


At the same time, a change in the “scope” does not lead to a change in the outer region. For example:
 foo = 10; with({ foo:20 }){ foo = 200; } console.log(foo); //10 


So, with is not such a powerful tool as let, but it is supported by most browsers.
I want to remind you that I don’t go against managing a scope using a function, but sometimes a function for a small scope is just too cumbersome.

PS I could consider more examples, but I do not consider it necessary to do this, since they are all the same in principle.
PS2 For spelling and more pleasant to read style thanks to habrayuzer ertaquo
PS3 Yes, I have problems with the Russian language, just look at the age and understand.

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


All Articles