Javascript global declaration - javascript

I've just started out with javascript and came across this line in a file called global.js There is only one line in the file. I'm not sure what does App do. Any ideas?
Filename: globals.js
//The Application
App = {};

it creates an object with a name of App... that's all it does.

I would assume that the idea behind the global.js file in your case is to include the file in your base html/template so that the variables in there can be accessed from anywhere in the app.
In some of our projects, we've had global files like this containing references to collections and "setting" variables, which is quite handy :)

It is creating an object named App in the global namespace. App has no functions or attributes (yet).

It (implicitly) declares a variable called App in a "global" context and assigns an empty object as its value. Assuming this is used on a web page somewhere, it's the same as declaring window.App = {}.
How this affects the rest of your application, we won't know until you post more relevant code.

This script just instantiate this empty Object. Probably, others scripts that ran along with this uses that object and depends that it is created there.

Related

Expressjs - global objects

I have an app written using express with connections to db, logger and other long living objects that requires to be open and accessed by multiple js files.
What are some of the techniques I could use to make the object "global" with minimal overhead/maintanence?
Thanks
In my opinion, you could put it in a foo.js file and use require('foo.js') to load it. This object is created only one according to This question
Define like this
//global.js
module.export = function(){
//define your global object and function here.
}
and call
require('global.js') in your script where you want

How to use javascript constant in javascript file from another javascript file

I have created one javascript file in which I have declared different string constants.
now in another javascript file I want to use those String constants from already created javascript file.
Is there any way to do this.
Thanks in advance.
If you declare your constants in file1 as global variables:
var someConstant = 42;
Then you can just use that variable in your other JS files. Just make sure file1 is loaded before you try to use them.
However, polluting the global scope like this come with it's risks, as those variables are easily changed.
Multiple ways.
Concatenate
Use a task runner like grunt to define a task that concatenates your files into a single one. This will not only allow convenient definition of constants but also improve performance.
There are other tools to do this, too. See Prepros for windows and codekit for Macs.
Modularize
If you are on client side, use a tool like require.js or browserify to define commonJS / AMD modules and require them as you need.
If you are on server side using node, this works out of the box for commonJS.
Load scripts in correct order, expose them through global objects.
You could load your constant defining script first and do something like this:
var constants = {
MY_CONST: 'Foo'
}
Your main, whi script could access this variable. If you omit the var keyword, the variable becomes globally available. Note however that this should be avoided.
You could even add a property to the global object (window on the client side).
Personally I like to use commonJS modules when working on projects that allow me to do so. Rob Ashton has an opinion on this that I would like to share.
When I can't use those modules in a convenient way, which would be the case when working with (custom) web-components because of their isolated scopes, I like to add a single script which creates
an Object like App. I use this object to expose modules, services & constants which can then be required by any component in a neat way:
App.myService.doSomething()
Create a file which contains all the constants and variables
Constants.js
const EMAIL = "xyz#gmail.com"
const PHONE = "9911223344"
var NAME = "Default name"
Access the Constants.js file in your HTML file
xyz.html
<script src="Constants.js"></script>
Now you can access the Constants in any of file inside a project

What's the correct way to use script files from other script files Meteor?

According to an answer to this question and the Meteor documentation, Meteor will automatically include all scripts in a package folder structure recursively with the deepest first. However, when I define a js class in a script in MyProject/sever folder the class is undefined if referenced from a top-level .js file. If I move the class definition to my top-level .js file above the if (Meteor.isServer) the class is defined correctly. What am I missing in structuring or including my javascript from external files?
EDIT:
The issue is more fundamental than just seeing my js class. I can't call a function or see anything in that private namespace that meteor 0.6 creates. Obviously there must be some way to reference stuff defined in another file or large projects wouldn't be possible in meteor.
As I suspected, this was related to my misunderstanding of javascript's (goofy hack) class declarations and globals. Changing:
function ClassFoo(){
this.bar = function(){}
}
to
ClassFoo = function ClassFoo(){
this.bar = function(){}
}
fixed it by making ClassFoo global. FWIW, note that var ClassFoo = ... will NOT work because it then becomes local to the auto-generated closure's namespace. Gotta love javascript's quirks.

Creating a "controller" script for Node.js

I'm creating a program in Node.js. I'm pretty new to programming anything other than small javascript functions for websites so please bear with me if my terminology/ideas are totally wrong.
I originally had the entire program in one giant (~500 line) script file. Several people suggested I split it up into separate classes, where each class only has one 'job' to complete. I like this idea as it has helped me really streamline my code and make it more modular and manageable.
My issue is: How do I access these classes from a central file?
For instance, pretend I have 3 classes, in 3 separate javascript files, all containing 3 functions each. I want to access and pass data to/from all of these from one central "controller" script. What's the best way to do this? Can I just require it into a variable, then access the script's functions like so?
var class1 = require('./class1.js');
class1.function1(); // call the first function contained in class1.js
Is such a thing even possible? Again, totally new to this.
NodeJS supports CommonJS modules. A CommonJS module provides three global variables: module, exports and require.
You can export your API by adding to the exports object and require these files just like other node modules (add ./ to indicate that it is relative to the current file), assign it to a variable and access the values you added to that files exports object:
// first-module.js
exports.hello = 'world';
exports.num = 23;
// main.js
var first = require('./first-module');
console.log(first.hello);
console.log(first.num);
You need to add functions to the exports object in class1.js.
require("./class1") will return this object.

How to correctly modularize a node.js project?

I'm creating a node.js project following the class constructor pattern:
function my_class(x,y){
this.x = x;
this.y = y;
}
The starting point of the project is the main.js file. Any class of the project must be able to access global objects (such as "world" and "socket") which are defined on main.js. I found 4 options:
I define my classes inside main.js. They'll have access to main.js's globals for being on it's closure, but main.js will become bloated.
I move the class to another file such as my_class.js and require() it. This doesn't work because my_class's instances will lose the closure context and no longer be able to access main.js's globals.
I move the class to another file and manually inject dependencies to it's constructor (ex: my_class(world,socket)). The problem is, code becomes much more complicated and weird semantics such as "my_instance.world" pop on the source, which is nonsense because "world" is not property of my_class.
I move the class to another file and require it using my_class = eval(fs.readFileSync(()) instead of require. This works just fine as my_class gets main.js's closure context, and is the solution I'm using, but seems hacky.
Which is the right way to modularize such node.js project?
If I understood you correctly the possible solution:
main.js:
(function(){
var global = "test"; // this you wanna have as a closure
var my_class = require('./my_class')(global);
my_class.go();
})();
my_class.js:
module.exports = function(global){
return {
go: function(){
console.log(global);
}
};
};
So it's similar to your 3. option
Your problem seems tricky because you have a circular dependency: main.js depends on the functionality of my_class and my_class depends on the data of main.js.
By putting the data of main.js into the global object you resolve the circular dependency:
main.js depends on the functionality of my_class.js
main.js depends on the data in the global object
my_class.js depends on the data in the global object
Now, to get rid of putting the data into the global object, implement a third module in let us say data.js. Then you require the sources like this:
main.js requires data.js
main.js requires my_class.js
my_class.js requires data.js
Since modules in node.js are singletons both main.js and my_class.js will get the same instance of data.js.
If you want to make variables in main.js available anywhere, then you can assign properties to the global object. See node.js global variables? for example. It would work fine as long as you don't over do it. With Neo's solution, you gain a little more flexibility for example with testing, because you can "inject" an arbitrary object into the module. Not every module has to use the same "global" per se.

Categories

Resources