Javascript functions, accessing variables - javascript

listofLOBs: function(data) { //passing data
var returnLOB = [];
console.log(data);
for (var i1r= 0; i1r < data.length; i1r++) {
var lob = new LOBslist();
lob.name = data[i1r].name;
lob.id = data[i1r].id;
returnLOB.push(lob); // storing in returnLOB
}
console.log(returnLOB[1].name);
$('#mainWrapper').find('select[name="lob-select"] option:selected').text(returnLOB[1].id); //using the returnLOB's object data to populate dropdown
return returnLOB;
}
In the above function i am storing objects in the returnLOB array and using it inside the function itself to populate a dropdown.
But say this is file1.js, i would like to access returnLOB's values from file2.js How can i do that? Thanks in advance.
Note: i have declared returnLOB[] globally too.(outside the above function)

To do what you want, you just need to remove var from your function so that you're not creating a local variable that shadows the global variable you've created in another file.
listofLOBs: function(data) {
// Here you're setting a global instead of a local
returnLOB = [];
You probably know this is a bad idea, and it would be better if you restructure your code so that you don't need a global
A simple solution is to have all code that needs the variable in one place with a self-executing function so your global is only exposed to the code that needs it
(function(){
var returnLob;
... contents of file 1, which write to returnLob
... contents of file 1, which read returnLob
})()

As long as you include file1.js before file2.js, it will work. Take jQuery as an example - or any JS library for that matter - if you include its source file before your code, you can use functions within it.
You want to include the files in the above order, then you can just call the function (listofLOBs()) in file 2.
Additionally, your variable declaration within the function is incorrect.
var returnLOB = []; // You're declaring a global.
should be
returnLOB = []; // because the variable is already declared - you just want a local copy.
Hope this helps.

You should be able to access any globals between files. In your example you defined returnLOB inside of a function so that won't be accessible but the one you claimed to have defined globally will be accessible by both files.
This also has been asked before so check out:
Javascript: Scope of a Variable across different Javascript files

Related

Does imported functions from the same source, have access to their source global variables?

OK i searched every site i knew, using every keyword i knew, but i found nothing close the subject i searched about, maybe the whole question is wrong, but anyway...
let's say we have a module named Index.js, which contains a STORAGE and two functions responsible for reading/writing to STORAGE.
var STORAGE = []
function writeStorage(data) {
STORAGE.push(data)
}
function readStorage(data) {
//find data in STORAGE... and return result as RES
return RES
}
Now, inside a file named write.js, we import writeStorage().
While in another file named read.js, we import readStorage().
And this is where the question rises,
Does imported functions from the same source, have access to their source global variables ?
i.e, can we modify STORAGE in index.js, using writeStorage() which we imported in write.js ?
and read STORAGE changes from read.js using readStorage() ?.
I want to provide clearer answer about that. There are two scopes for functions: lexical, and dynamic. Dynamic means, a function will search variables in the area, where it was called:
let someVar = 'global';
function dynamicScope () {
someVar = 'dynamic';
console.log(somevar);
}
dynamicalScope(); // will display 'global'
Lexical means, the function will search variables where it was written/declared:
let someVar = 'global';
function lexicalScope () {
someVar = 'lexical';
console.log(somevar);
}
lexicalScope(); // will display 'lexical'
But in JavaScript, there is no way to use dynamic scope, so all function will search variables where it has been declared/written.
DO NOT PAY ATTENTION ON DETAILS, IT'S JUST A PSEUDO-CODE.
Short answer: Yes, that's possible.

Node.js run file inside another file

this is my current code
function includeClass(classname, ctx) {
var txt = fs.readFileSync("socket.io/" + classname + ".js");
return txt;
}
//define globals here
var _PLAYERS = {};
var _SPAWNPOINTS = [];
vm.runInThisContext(includeClass("vector"));
vm.runInThisContext(includeClass("class"));
vm.runInThisContext(includeClass("connectionHandler"));
vm.runInThisContext(includeClass("game"));
But that way, class.js file can't access variables from global scope or other files. because now i get errors like, _PLAYERS or require is undefined. I've tried eval() too, but it didn't do anything at all.
How can I run these js scripts in main script so they get interpreted as 1 whole?
https://nodejs.org/api/vm.html#vm_vm_runinthiscontext_code_options:
Running code does not have access to local scope, but does have access to the current global object.
Your _PLAYERS variable is not truly global, it is local to your script. As well as some other variables (like require) which are also in the module scope.
You can try to assign the needed variables to global object, however, I am not well aware what side effects and complications may follow.

Make js file not accessible through web console

This is most likely a very simple one.
I have created a game in canvas and js. However I stumbled upon a problem. As I can access the variables and code inside the chrome console, I can change f.ex. the player score to whatever I'd like. This is not very good.
Is there some way I can make the file and variables non accessible through the console for players to use?
Thanks!
You can put the whole script into an IIFE so that any variables declared will be scoped to the just-invoked function, rather than be on the top level and accessible anywhere. For example:
(function() {
var playerName = 'bob';
var turnCount = 1;
// do stuff with playerName and turnCount,
// they won't be accessible or changeable from the outside
// you can declare functions and such here as well
// which will also only be accessible from the inside
})();
Like this, referencing playerName from the console will fail.
you can use a proxy.
javascript proxy
or you can make an IIFE and expose only the required functions such as:
var App = (function() {
var test = '';
var init = function() {
App.test = 'test';
};
return {
init: init
};
})();
or define your properties as not writable with Object.defineProperty()

interacting with javascript through the chrome console [duplicate]

This question already has answers here:
Console access to Javascript variables local to the $(document).ready function
(8 answers)
Closed 6 years ago.
I'm using a shopping cart api to build an ecommerce website. The creators made an sdk and then you have to make your own .js file for some other functions.
While debugging I would insert a console.log(etc..) anywhere in my .js file so that I could debug object options and etc..
But I would like to be able to use the sdk as a live tool, so instead of having to edit my .js file with new console.log() lines, I'd rather just be able to type object.color_code and have the console output that string for the object color code. At the moment though it just gives me uncaught reference error, object is not defined.
I think this is because my custom .js file has all of it's script inside a $(function() { EVERYTHING }); SO, when I try to call anything in EVERYTHING from the console it says it's undefined, but if I just used console.log inside EVERYTHING it would work. So is there a way I can get around this?
Feel free to explain why it isn't working but I'd like a way to enable this, don't tell me there isn't a way, even if I have to prefix what I want with the .js file it's coming from each time, I don't mind
You were correct in that all of your variables inside the function are only being defined locally, and thus can't be accessed via the console. However, in Javascript there are at least two options for setting global variables from inside functions; If you use these to declare a variable you want to access from outside the function, it will work:
Assign a value to an undeclared variable: varname=value;
Assign the variable to the window object: window.varname=value; or window['varname']=value;
A possible workaround is to expose the object(s) that you want to debug in the global scope:
(function() {
var privateStuff = { foo: 'bar' };
// make privateStuff public for debugging purposes
window['debugObject'] = privateStuff;
})();
document.write(debugObject.foo);
If you want to expose several objects with rather common names that are likely to collide with existing ones, make sure to expose them within an object with an uncommon name rather than directly:
(function() {
var x = { str: 'this is' },
y = { str: 'a test' };
window['debugObject'] = {
x: x,
y: y
};
})();
document.write(debugObject.x.str + ' ' + debugObject.y.str);
If you're happy to change the source file then you could export whatever you want to access from EVERYTHING as a global.
$(function() {
//EVERYTHING
...
window.Ireply = window.Ireply || {};
window.Ireply.object = object;
...
});
console.log(Ireply.object); // some object
You can change a declaration like
$(function(){
var cart = {};
})
To
var cart;
$(function(){
cart = {}
})
Or
$(function(){
var cart = {};
window.cart = cart;
})
But you will want to avoid polluting global namespace. You will also want to be careful about using globals inside callbacks or loops where you can run into unexpected behaviors since local variables scope is often important to be kept local

Access for global variables JavaScript unit testing

Hello I am new JavaScript unit testing and I'm using Mocha.js and Chai.js
What I want to do is simply figure out how to check the value of a global variable in a seperate js file. Here is my code
Here is the main.js file (code to be tested) Just has the variable I want to test against.
//main.js
var foo = 9;
Here is my test file
var assert = require("assert")
var expect = require('chai').expect
var fs = require("fs")
var vm = require("vm")
function include(path){
var code = fs.readFileSync(path,'utf-8');
vm.runInThisContext(code,path);
}
describe('Global', function(){
include('lib/main.js');
it('Should check if value is matching', function(){
expect(foo).to.equal(9);
});
});
Again, I'm new to unit testing in JavaScript. Any help will be greatly appreciated. The error I get back is foo is not defined which tells me that it can't access the variable, so how can I access it? Thank you in advance for the help.
var foo = 9; does not declare a global variable, it declares a local variable. In Node.js, a local variable declared in the outermost scope of a module will be local to that module.
If you want to test the value of a local variable declared in another file, your best bet is probably to read the contents of that file into a string (using fs.readFileSync, perhaps) and then eval() the string, which should define the variable in the current scope.
That will only work if the local variable is declared in the file's outermost scope. If it's a local variable inside a function, for example, you're out of luck (unless you want to do some gnarly string parsing, which would stretch the bounds of sanity).
Your global object is usually window
a global var foo = "test"; is the same as window.foo = "test"; or window['foo'] = "test";
Window is not defined when mocha is run in node, but this blog post uses "this" combined with a self-invoking function to get the same result.

Categories