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.

1
  • JS knows nothing about files and folders. Commented Mar 20, 2015 at 3:37

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

As compared to var width as shown in the question, which also creates a global variable.
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.
You can also inspect globals in the window object if you don't explicitly assign to window. I agree with you though.
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
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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.