Reputation: 1632
I have a variable and a function in a file hello.js
as below:
I want to call the above function and access the variable from another file, say app.js
, (both files in the same folder) var width = 500;
function reset() {
//some code
}
How should I be doing it.
Thanks.
EDIT:
Actually,
I have the above variable and function inside another function, (I didn't mention earlier, I thought I will take hints and make it work):
Its like this:
var Engine = (function(global) {
var width = 500;
var canvas = doc.createElement('canvas'),
canvas.width = 500;
function reset() {
//some code
})(this);
Now I am trying to access these function and variable, like below:
console.log(Engine.canvas.width);
Engine.reset();
It doesn't recognize reset()
and canvas
.
Upvotes: 3
Views: 726
Reputation: 307
//app.js
var Engine = function(global){
var engine = {
width: global.width,
reset: function(newValue){
something.width = newValue;
global.width = newValue;
}
}
return engine;
}
var myEngine = new Engine(window);
console.log(myEngine.width); myEngine.reset('600px');
//secondFile.js //window.width = '500px'
Upvotes: 0
Reputation: 9388
Per your edit, you would have to expose the variables by returning/exposing them (or you could create a constructor with methods/properties for an Engine instance...)
var Engine = (function() {
var width = 500; // private
var canvasEl = document.createElement('canvas');
canvasEl.width = 500;
function reset() {
// some reset code
}
return {
canvas: canvasEl,
reset: reset
}
})(this);
console.log(Engine.canvas.width) // 500
Upvotes: 2
Reputation: 307
you can assign anything to the window object, and then it will be able to be accessed from anywhere.
window.width = 500;
then you can do use window.width to get the value from anywhere.
Upvotes: 0