3

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.

Ejaz
  • 1,504
  • 3
  • 25
  • 51

3 Answers3

2

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
Jack
  • 9,151
  • 2
  • 32
  • 44
0

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.

loveNZ
  • 307
  • 2
  • 12
  • As compared to `var width` as shown in the question, which *also* creates a global variable. – nnnnnn Mar 20 '15 at 03:42
  • yes, it is true, but I think assign to window object make the global variable more explicit, which I think it is good, as you can always inspect the window object to see what are the global values you have. – loveNZ Mar 20 '15 at 03:44
  • You can also inspect globals in the `window` object if you don't explicitly assign to `window`. I agree with you though. – Felix Kling Mar 20 '15 at 03:46
  • If you're going to add variables to the global scope, using names such as `width` should be strongly reconsidered as it is too generic and too likely to be used by other code – jasonscript Mar 20 '15 at 07:48
0
//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'

loveNZ
  • 307
  • 2
  • 12