How to access variable from another function?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
23 views
Suppose there is a hypothetical code:

$(window).on('load resize', function() { var img = document.createElement('img'); img.src = 'img/bg.jpg'; var imgAspectRatio = img.naturalWidth/img.naturalHeight; var $bg = $('.bg'), bgAspectRatio = $bg.outerWidth() / $bg.outerHeight(); if (bgAspectRatio > imgAspectRatio) { $bg.css('backgroundSize', 'cover'); } else { $bg.css('backgroundSize', 'auto ' 500px'); } });


How you can make the variable Declaration imgAspectRatio out with the condition that it remains in local scope and can be used by other functions? Particularly interested in the answer to the question, what are common practices (best practices) for dealing with such situations, what are the patterns used? I apologize in advance, if not correctly formulated a question, in js I'm new.
by | 23 views

3 Answers

0 like 0 dislike
There is such a practice

(function(w){ var getImgAspectRatio = function(){ var img = document.createElement('img'); img.src = 'img/bg.jpg'; return img.naturalWidth/img.naturalHeight; }; $(w).on('load resize', function() { var imgAspectRatio = getImgAspectRatio(); var $bg = $('.bg'), bgAspectRatio = $bg.outerWidth() / $bg.outerHeight(); if (bgAspectRatio > imgAspectRatio) { $bg.css('backgroundSize', 'cover'); } else { $bg.css('backgroundSize', 'auto ' 500px'); } }); })(window);
by
0 like 0 dislike
Unfortunately, the variable must always have a scope, either global or a local. So it is not possible to provide a variable outside any function, with the expectation that it will remain visible only to this function, or specifically a limited set of other functions. This contradicts the paradigm of mission variables. There are only workarounds (the gardens), but essentially all the same variable has a scope.
by
0 like 0 dislike
can declare it globally, that is, not within a specific function, and writing a function
by

Related questions

0 like 0 dislike
2 answers
0 like 0 dislike
3 answers
0 like 0 dislike
1 answer
asked Apr 3, 2019 by JackShcherbakov
0 like 0 dislike
2 answers
0 like 0 dislike
2 answers
110,608 questions
257,187 answers
0 comments
40,796 users