design patterns - Javascript - Separating variables in different script -
design patterns - Javascript - Separating variables in different script -
i have few pieces of scripts written already. however, variables within different script certainly collide each other upon import
some of examples scripts
the next script a
<script> var vx = 0; var vy = 0; var d = null; function init() { ...} function commentbox() { ... } commentbox.prototype.create = function() { ... } </script>
the next script b
<script> var vx = 0; var vy = 0; var x = 0; var y = 0; var p = null; function init() { ...} function ball() { ... } ball.prototype.create = function() { ... } </script>
upon import, variables , methods certainly collide each other.
here's question. possible separate them without need modify name? know there exists design patterns how can accomplish this?
i have been using prototype pattern various "object" in these script don't know how when have apply whole script. possible have nested prototype?
the scoping of variable (the context), in javascript resolved through functions.
if create variable way:
<script> var = 10; </script>
in reality implicitly :
<script> window.a = 10; </script>
what can shield variables beingness read wrap variables within phone call invoked function look (iife), acts closure:
it's wrapping function parentheses, , treat whole block it function name, add together parentheses execute code straight (otherwise have needed phone call function)
<script> (function(){ var = 10; })(); </script>
creating variable way, instead of making variable available through window. create variable within closure, , live long closure live in object stack.
this way can this;
<script> (function(){ var b = 20; var = 10; window.c = 40; })(); </script>
if want 2 closures communicate, can pass variables window , grab in other closure
<script> (function(){ var d = window.c + 5; //prints 45 })(); </script>
in (a tiny) bit cleaner way, can pass variables closure:
<script> (function(c){ var d = c + 10; //prints 50 })(window.c); </script>
finally, scripts injected within html, have main global variable window means these snippets above can either in same html file, or in separate js files, careful order of inclusion of files though, closures utilize external variables, have variable instantiated in file included before;
(ps: there other practices, when sharing variables such creating 1 variable attached window , utilize variable main variable application (instead of using window))
something this:
(function(){ var window.app = {}; })();
which can used somewhere else way:
(function(app){ app.test = "something"; })(window.app);//or app
i hope works;
javascript design-patterns
Comments
Post a Comment