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

I am learning how to write applications using NativeScript. I think the best way to learn is to do it. For this reason, I am building a basic application.

In this application, I am trying to create a function and a variable that I can access through ALL view models and other code in the application. In an attempt to do this, I decided to add a function and a variable to the application object.

In NativeScript, an application is initialized with the following code:

app.js

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

I decided that I could fix this and add a globally visible function and a variable like this:

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

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

view /home.js

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

However, when I run this code, an error appears indicating that the application is undefined. I do not quite understand this. I thought that since the application is defined / created in app.js, it will be globally visible. However, this does not seem to be the case. At the same time, I'm not sure what to do.

+6
source share
1 answer

Use global namespace. In app.js :

 var application = require("application"); application.mainModule = "main-page"; global.myVariable = 'some value'; application.start(); 

Then you can use global.myVariable anywhere in the application.

+12
source

All Articles