Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to create a globally-accessible library myLib in Javascript. My library should do the following
Keep a somewhat persistent variable myLib.tax.
-- It should survive through the handling of a typical browser user event, at least in simple cases. I don't care if it survives longer than that or not.
-- external code should be able to set the value of this variable, either through a setter or otherwise.
Has a function myLib.applyTax(var price).
-- return value is price + myLib.tax.
-- I don't care what it does if either price or tax is not a number.
Lastly, a brief example of how to call this from another file, in such a way that:
-- for example, file A might set the value of the tax, then file B might apply the.
-- this works even though files A and B are unrelated.
The purpose of this question is for me to understand code and state encapsulation and how to use them from elsewhere.
EDIT: For the benefit of anyone seeing this later, what I did not understand when asking this question is that referring from javascript file A.js to javascript file B.js is a difficult problem unless that is enabled externally, for example in the html. For more detail, see How do I include a JavaScript file in another JavaScript file?
From your comments I see you would implement a Singleton Pattern in C# through static methods and data.
In Javascript you can do the same by managing the closures and putting that data into the outermost one, which would then be accessible to all code due to lexical scoping.
But I'd rather avoid singletons every day. Instead, use dependency injection as follows. This is just an example to show the technique, you'll have to code an actual solution yourself.
var lex = (function () {
var privatedata;
function privatemethod()
{
}
return {
publicmethod1: function (arg1, arg2) { ... },
publicmethod2: function (arg1, arg2) { ... },
getPublicData: function () { ... }
};
}());
This incapsulated object is then injected wherever you need it:
function consumerCode(lexicon)
{
...
}
consumerCode(lex); // injects the lex instance into the consumer code
By having only one instance and passing that same instance around wherever you need it, you will have pretty much what you were asking for.
This technique is not limited Javascript but also useful in C#. But in Javascript with loose typing it is especially powerful.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Every time I see JS namespacing referenced it is implemented with an object expression. If I want to be sure that my namespace exists before it is assigned any properties, can I instantiate it by way of function declaration?
e.g.;
function namespace() {}
vs
let namespace = {};
The former being hoisted, and guaranteeing that properties I append to my namespace won't encounter an "undefined" error.
I know it works at least for my basic tests, but are there pros/cons to this?
Edit: Another example: https://jsbin.com/nuquxuxinu/edit?js,console
Edit: Bergi provided some good clarification, but I still need to be convinced as to why using a function as a namespace is a bad idea.
ANSWER: Since my question was marked as "opinion based" I can only deduce that there is no technical reason why you shouldn't use a function for a namespace.
No, you should not make your namespace object a function object unless you need it to be callable. If the function does nothing (like in your example), don't use a function.
Hoisting does not have any benefits for you. The variable declaration let namespace is hoisted just as well. What is actually important is that the members of your namespace are created before you use them, and they are created by assignment. Just put them in the right order in your file - first the namespace object instantiation, then the properties of that object (if they were not already created as part of it in an object literal), last the code that uses the namespace.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've started to accumulate quite a few lines of Javascript code for a website. Everything has been in one file so far and that file is becoming impossible to maintain. If there is an error in one line, the entire file breaks.
I've tried splitting the code up into multiple files but there are some shared methods across objects like: validateEmail(address).
Right now, I have my code organized into objects, like so:
var ProductPage = {
addToCartBtn: "#add-to-cart",
init: function() {
ProductPage.initAddToCartPopup();
ProductPage.initSidebar();
...
},
...
};
Then, I call ProductPage.init() on $(document).ready.
My issue is: when splitting ProductPage into a separate file as ContactPage, for example I cannot access ContactPage.validateEmail(). I believe this is because my code is wrapped in jQuery's:
(function ($) {
...
})(jQuery);
Does anyone have insight on how they have organized large systems of Javascript? Also, I plan on doing optimization with putting all of this into one file and compressing it. So, any method which will benefit both maintainability and ease of optimization would be awesome.
validateEmail like methods are functional in my opinion. By functional I mean, y = f(x). These functions are not changing the state but returning an output which are being computed on the passed input.
You might want to keep all this utility functional methods in a separate module and tag it to a global namespace. Make sure to load this(these) utility module(s) before utilizing them.
You can use require.js for dependency management.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
When is it GOOD to declare a global variable in JavaScript? Typical advice concerning global variables includes:
I sometimes encounter situations where it is critical that the value of a variable is available for the duration of the activity of the user. For example, knowing the state of which page is open. Another situation is when there is a long process with lots of smaller functions, but some value needs to be maintained throughout the process. Rather than passing an argument from function to function to function, and hope it doesn't get to confusing, just create a global variable.
In general, it's bad practice to declare global variables.
Can cause problems with "Namespace Pollution".
Duplicate variable declarations of the same name inside and outside of a function.
Global variables are slower to look up than local variables.
It's easy to forget that you declared the global variable, because it's out of site from the current code you are working on.
Tracking and debugging a global variable is hard.
Asynchronous use of the global variable could cause concurrency issues.
Situations where it would be good to declare a global variable?
A constant that has a lot of characters in it, that is used a lot. Reduce the size of overall code.
Saving the state of the current condition of something that must be monitored, and available at all times to more than one function.
It seems to me that the requirements would be:
High usage and/or
Required by at least two different functions that are outside the scope of each other.
Examples:
Object with many characters:
var dc = document;
var isTheMenuDisplayed = dc.getElementById('MainMenu').style.display;
Monitor Current State:
What page is currently displayed:
/* The state of what page is currently display, must be available to
the entire application at all times.
Variable is declared outside of a function enclosure.
*/
var whichPageDisplayed = '';
function changePage(pageNameToOpen) {
if (whichPageDisplayed === 'home') {
close the home page;
open the new page;
//Make sure to record what the new current open page is
whichPageDisplayed = pageNameToOpen;
};
I'm looking for reasons about when it's GOOD to use a global variable.
If global variables are considered always bad, then how do I deal with the above two situations without a global variable?
The "Asynchronous use of the global variable could cause concurrency issues" reason shouldn't be exclusive to global variables. Asynchronous use of anything could cause concurrency issues, so I don't see how that is an argument against global variables.
The "It's easy to forget that you declared the global variable, because it's out of site from the current code you are working on" reason seems like a coding discipline issue. If I saw that there was no var = thisVar statement anywhere to be found in that section of code, I'd think to myself, "Maybe I declared it as a global variable?". Then I'd do a search to find it.
"Tracking and debugging a global variable is hard" I have a "Search All Files" option in my code editor. It searches all the files, and shows me every line of code where the search found a match. It's not that hard. Depending on what browser and what developer tools I'm using, an error msg may show me the exact line of code where the error came from.
Reducing the overall code size isn't a valid reason. Minifiers will knock it down. Besides, if you have something like your example of dc.getElementById('MainMenu').style.display, you want a method to help you. Such as getDisplayStyle('MainMenu'). Doing that is just good practice, as it allows you to keep the logic in one spot.
Saving state isn't really a valid reason either. Keep your code in modules. For example, your code turned into something a bit "better":
PageState = {
changePage: function (pageNameToOpen) {
if(this._currentPage == 'home') {
/*******/
}
this._currentPage = pageNameToOpen;
},
getCurrentPage: function () {
return this._currentPage;
}
};
PageState.changePage(pageNameToOpen);
The only times you should consider a global variable is if a library requires it, or if you need to setup configuration options on something before that "something" exists (and you are not using AMD type modules). For example, one of the popular WYSIWYG editors out there looks specifically for a global variable that defines some constants for setup.
Basically, for almost every possible usage of global variables, there is counter argument for wrapping it in a module of some sort.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a page I am building, and our solution to a problem involved wrapping some code inside a function then calling that when required.
Now the page is growing, and each item has its own function. According to D. Crockford each function is put in a VAR anyway so:
function functionName(){}
is equivalent to:
var var1 = functionName(){}
So now we have LOTS of vars in the page (I have also written them specifically in the latter format as Mr. Crockford promotes) and I am getting worried this creates too many variables (not sure this will cause any issues, performance or otherwise). I am thinking of making a single Object Literal and adding each function as a value to a key. This I think will reduce all these vars into a single manageable unit and reduce the amount of variables I am using (and avoid any potential issues) - or will it?
Thanks!
var keyword is actually being used in order to manage variable scope.
Not using var keyword makes the variable a global one. The memory occupied by the variables are cleared when the variable isn't used anymore. Most of the modern browsers contains a garbage collector responsible for freeing up the unused spaces. So it's suggested that using var keyword in blocks would make your js interpreter search less for the variable, otherwise it will search the whole document in order to get the value.
In performance terms it doesn't matter, you can use as many variables as you want, the performance only will be affected by the tasks performed in the function.
As you keep increasing the variables, the heap limit set by the relevant JS engine will come into play.
For eg - V8 engine seems to have it set to 1.4 GB
If you do ever run out of that, it's high time you recheck the code & stop blaming JS.
On a serious note, from a practical point of view, that's an enormous limit, which tells you that you don't need to worry about it so much.
Besides your friendly neighborhood GC will always keep cleaning up & ensure you live lavishly with variables.
Encapsulating your code in a namespace is a good idea but you won't save memory or get a performance boost that way. From performance perspective both ways you've shown are the same.
There is a convention to avoid nameclashing however based on reverted domain - imagine a JS lib made for SO:
// The following two lines are to protect namespace from overwriting and allow to
// extend them easily
if (!com) var com = {};
if (!com.stackoverflow) com.stackoverflow = {};
com.stackoverflow.renderSomething = function(){
// Some very clever code here
};
There is nothing else you can gain this way but it's worth to organize your code this way.
And just to clarify:
function functionName(){};
is almost the same as
var functionName = function(){};
Almost because in the first form functionName is defined at parse-time and the latter form defines functionName at run-time.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Does PHP interpret code in the same way that JavaScript does? Upon some research, I've gathered that JavaScript programs are run in a so-called 'two-pass' read. The first run gets the syntax and function definitions of the program. ('Parses' the data so to speak), and the second run - well - runs the data. Does PHP work the same way? If not, how does PHP interpret code?
What are the general functions of a PHP interpreter?
Most programming languages work that way, maybe save for batch files. The source code is parsed into tokens and a syntax tree is created which is then evaluated. These are three separate steps and it's practically a lot simpler to keep them separated. If you'd want to mush them together so code got executed while it is being parsed, that means the parser would have to read just enough to get one full block of something which is executable, then hand that over to the runtime, which would then have to hand control back to the parser. It's a lot easier to do everything one by one.
What you've described in the question is a very tiny aspect of how the interpreter works.
PHP does indeed do this: you can tell because it is valid to have a function call higher up in the code than the actual definition of the function that is being called.
<?php
myFunction(); //this is only valid here before the function itself because of two-pass parsing.
function myFunction() {
.....
}
myFunction(); //in a single-pass system, the function call would have to be here, after the function itself.
?>
If you only had one pass, you would only be able to call a function after the function itself had been defined. Some languages do work this way (C and Pascal are good examples). These languages require the use of header files if you want write a function call earlier in the code than the function itself is defined.
The difference is that those languages are compiled, which means that the code is only actually run once everything has been built into an executable. The single-pass approach with header files wouldn't work in an interpreted environment because while the header may allow the compiler to accept the function call as valid, an interpeter would still fail because it simply wouldn't have the function available to call.
For this reason, pretty much any interpreted language is going to use this two-pass mechanism.
However, as I said, this is just a small part of the overall design of an interpreter.