简体   繁体   中英

How to make a global javascript function and variable?

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 .

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

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.

//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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM