A page has imported the js, but the methods in it cannot be called..(in the same folder)
The code is as follows html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="./AgentGetway.js"></script>
</head>
<body>
<script type="text/javascript">
console.log(AgentStatus['host']);//这个地方说AgentStatus is not defined
</script>
</body>
</html>
The content of js is as follows:
var AgentStatus={
host :'127.0.0.1'
};
or:
var AgentStatus=(function(){
return {
host:'127.0.0.1'
}
})()
I can’t get it, please give me some guidance...
The questioner just wants to get the reference to the global variables in js. Such a simple requirement does not necessarily have to be modular. Just delay the acquisition time:
Use the chrome browser console --network to see if your js file is loaded. If it is loaded, check if there are any errors in the console.
The essence of this problem is the modularization of JS. There were many solutions before, such as AMD, CMD, requireJS, CommonJS... There are many of these online, you can search for them yourself.
Now let me tell you about the solutions that have been incorporated into the ES6 specification:
First you need a build tool webpack or gulp. In comparison, the former is more popular now, but the learning cost is slightly higher, or the kind of already prepared scaffolding such as vue-cli
npm i babel
This tool is used to parse ES6 code into JS code supported by most browsers. There are also tutorials on how to implement this step in Babel. Of course, if you use a scaffolding like vue-cli, it will help you configure everything, including local services, so you can skip this step.Use ES6 specifications to write the language and solve your problems
tips:
The situation in which you reproduce the problem should be rarely encountered in real project development, because this is a problem that has been solved a few years ago, and it is a problem that large projects will definitely encounter
The core of this problem is JS modularization. There are many and extensive knowledge points involved in this. If you are interested, it is better to learn about it. Of course, you can also skip it and look at the modularization of ES6 specifications directly
module.export = the function you want to export;
Import the exported function on another page.
require.js