How to create a new istance of a global variable in Javascript

How to create a new istance of a global variable in Javascript



at the beginning of my code, I create a new instance of my global variable DT, but when I try to reassign it a new object in a method my global variable doesn't change.


const functions = require('firebase-functions');
const DecisionTree = require("decision-tree")
var firebase = require('firebase-admin');
const cors = require('cors')(origin: true);


......

var boards;
var dt;
var training_dat;

var class_name = "NextMove";
var features = ["C1", "C2", "C3", "C4", "C5", "C6", "C7", "C7", "C9"];

ref.once('value').then(function(snap)
boards = snap.val(); // query all data
training_data = new Array();
for(var B in boards)
training_data.push(boards[B]);

dt = new DecisionTree(training_data, class_name, features);
// HERE dt is a model with 500 rows.
);



exports.train = functions.https.onRequest((request, response) =>
.....

dt=new DecisionTree(new_training_data, class_name, features);
//HERE dt is a model with 1000 rows
response.send(output: "Training");
);

exports.DOSOMETHING = functions.https.onRequest((request, response) =>
// if i call dt here it is still a model with 500 rows.
response.send(output: "Done");
);



So I start my script, I get that dt is 500 rows.
If I call "train" I get that it is 1000 rows.
But when I call "DOSOMETHING" my variable dt has still 500 rows, like the precedent method didn't affect him.



I'm sorry it may sound stupid but I can't figure it out;




1 Answer
1



Node.js does not put variables declared with var into global scope. (see related Question).



Whilst you can create a global by assigning a value to dt without using the var keyword, it errors in strict mode . You could try assigning a value to global.dt instead of dt to create and access a global value without strict mode errors.


dt


var


global.dt


dt



Per Node.js documentation requiring a module multiple times always returns the same cached module.exports object that was created when the file was first required. Hence you should also be able to require an empty js file, say appdata.js, anywhere you want to access a common name space object within an applicataion.


module.exports


appdata.js



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)