简体   繁体   中英

Is it possible to access a regular javascript variable from within a JQuery function?

I have an HTML file which imports two files:

graph.js and main.js

The main file contains logic which accesses a phone's accelerometer/records acceleration and it is a purely javascript file. The Graph.js file contains a single JQuery function $(.....)

Is it possible to access a variable in main.js from graph.js?

Yes jQuery is written in JavaScript and it can access any variable declared in that page via import of other JavaScript files. As you are trying to access variable in onload of document, I don't see any problem, because other scripts should already have been loaded before that.

是。

如果在全球范围内,是的。

It should be, so long as the main.js loads first and if you set it as a global variable.

You make a global variable by creating it outside of a function. If needed, you can create it outside a function, then set it inside a function in the main.js file.

You can freely share variables between different JS files (a jQuery file is just a JS file) in several different ways:

  1. Define the variables in the global scope, then they can be accessed anywhere.
  2. Define variables on the window object. This makes them globally accessible even if your code defining the variables isn't in the global scope.
  3. Define variables as properties on any object that you can get to from your code. So, if you have a global config object called myConfig , you could define properties on it like myConfig.count = 0; and you can then access myConfig.count from anywhere. This is often referred to as namespacing and creates only a single global object which you then add multiple properties to.
  4. Define a globally accessible function that returns your data that you can call from anywhere.

When designing how this works, remember that it's generally better to introduce as few globally accessible symbols as possible because each one is an opportunity for a conflict with some other code in the page.

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