开发者

How to access JavaScript module pattern in my case?

开发者 https://www.devze.com 2023-02-25 05:44 出处:网络
I have defined the following module in MyModule.js: MyModule.js: MyModule = { controller: { paintCar: function(color){

I have defined the following module in MyModule.js:

MyModule.js:

MyModule = {

    controller: {
       paintCar: function(color){
            //PAINTING PROCESS
       }
    },

    tester: {
        ...
    },

};

Then, I have another javascript file, other.js:

other.js:

MyModule.controller.paintCar('red');

My index.html

<body>
    <script scr="MyModule.js"></script>
    <script src="other.js"></script>
  </body>
开发者_开发技巧

All these files are put under WebContent directory of Eclipse Dynamic Web Project.

In other.js when I try to run the above code, I got error "MyModule is not defined". Why?


You misspelt src here: <script scr="MyModule.js">. This would have been picked up by basic automated QA testing.

(Original answer before the theory was confirmed) Presumably, because you aren't loading the script files properly. Since you haven't shown us the code that does that (or even told us what environment you are using) it is hard to say exactly how you went wrong.

Assuming you are using client side JS in a webpage, your code should look something like:

<script src="MyModule.js"></script>
<script src="other.js"></script>

Order is significant. End tags are mandatory. Self-closing tag syntax is unacceptable (unless the document is served as application/xhtml+xml)

(This uses HTML 5 syntax. For HTML 4 / XHTML 1, add a type attribute. For HTML 3.2, add a language attribute)


You haven't mentioned your environment, but generally you have to ensure that the JavaScript in MyModule.js is executed before the JavaScript in other.js, because you need MyModule.js to set up the MyModule variable.

How you do it will vary by environment. In a web browser, you'd do that by putting in two script tags, first one for MyModule.js then the one for other.js (although frequently, for use on websites, you want to have a build process that combines your scripts into a single file to minimize HTTP requests). In NodeJS, there's the whole require mechanism.

Update based on your edit:

Looks like a typo:

<body>
    <script scr="MyModule.js"></script>
             ^^-- here, they're transposed
    <script src="other.js"></script>
</body>

If that typo isn't really in your file, then look to see that the files are where the web server expects, that the web server isn't being thrown by capitalisation, that sort of thing. Fundamentally, that's correct.

0

精彩评论

暂无评论...
验证码 换一张
取 消