Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a global variable / function in JavaScript (specifically NativeScript)

I'm learning how to write apps with NativeScript. I believe the best way to learn is by doing. For that reason, I'm building a basic app.

In this app, I'm trying to create a function and a variable that I can access across ALL of the view models and other code in the app. In an attempt to do this, I thought I would add a function and variable on the application object.

In NativeScript, the app is initialized using the following code:

app.js

var application = require("application");
application.mainModule = "main-page";
application.start();

I figured I could piggy back on this and add a globally visible function and variable like so:

application.prototype.myFunction = function() {
  console.log('I made it!');
};
application.myVariable = 'some value';

Then, in my view models, or other code, I could just do something like the following:

views/home.js

application.myFunction();
console.log(application.myVariable);

However, when I run this code, I get an error that says that application is undefined. I do not fully understand this. I thought that because application is defined/instantiated in app.js that it would be globally visible. However, it does not seem to be. At the same time, I'm not sure what to do.

like image 626
user687554 Avatar asked Jul 19 '15 14:07

user687554


People also ask

Can you use a global variable in a function JavaScript?

Global ScopeGlobal variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.

What is a global JavaScript variable?

Global variables are declared outside of a function for accessibility throughout the program, while local variables are stored within a function using var for use only within that function's scope.


1 Answers

Use the global namespace. In your app.js, code:

var application = require("application");
application.mainModule = "main-page";

global.myVariable = 'some value';

application.start();

You can then use global.myVariable anywhere in your app.

like image 151
FlipOne Avatar answered Sep 27 '22 17:09

FlipOne