Since I'm converting the Javascript code to node.js, I'm changing the old code to adapt it to ES6, using "Class< /strong>" and "Module" instead of just using the "Function" component.
I updated the server side first and everything went well. But now, I'm trying to get into the client and I'm having trouble converting the old encoding to the new one.
In the following example you can find 2 applets:
The "module" applet consists of 2 files: "FooClass.js" and "Foo_mod.html".
"Components" include "FooComp.js" and "Foo_comp.html".
All 4 files are stored in the same folder. Both applets should display an alert message "x = 7", but the "Module" applet does not, while the old fashion one Done right. However, when you press Ctrl and click the js file name in VS Code, there is no problem in reaching the js file from the html code. So there must be something wrong with my new code, but I can't find it. If anyone can help me, thanks in advance...
FooClass.js:
class Foo { constructor() { this.foo = ""; } cinq (x) { //(real)->real return x + 5; } } module.exports = Foo;
Foo_mod.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page2</title> </head> <body> <script type="module" src="./FooClass.js"></script> <script type="text/javascript"> var fx = new Foo(); var x = fx.cinq(2); alert("x = " + x); // must display "x=7" </script> </body> </html>
2 - Old method applet: (works fine)
FooComp.js
function cinq (x) { //(real)->real return x + 5; } // end of file FooComp.js
Foo_Comp.html:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>FooComp</title> </head> <body> <script type="text/javascript" src="./FooComp.js"></script> <script type="text/javascript"> var y = 2; var x = cinq(y); alert("x = " + x); // must display "x=7" </script> </body> </html>
P粉6748763852023-09-08 09:35:10
You should modify the FooClass.js
file to use the ES6 export
syntax instead of module.exports
:
export class Foo { constructor() { this.foo = ""; } cinq(x) { return x + 5; } }
You can use the import
statement to import the
Foo
class:
<script type="module"> import { Foo } from "./FooClass.js"; var fx = new Foo(); var x = fx.cinq(2); alert("x = " + x); // should display "x=7" </script>