Extend JavaScript Class from separate file

2019-06-04 01:20发布

问题:

I'm sorry to ask quite a dim question as I'm very new to OOP in JavaScript.

I'm trying to use John Resig's Simple JavaScript Inheritance method, and ideally I'd like to store this within say utils.js, and then use it (using Class.extend), throughout the range of script files that my project uses. Is this possible? I've noticed that if I create a subclass from within my utils.js file, I can then create a new instance of that class from a different script, so that makes me think it might be possible. Does it have something to do with the method being wrapped in an immediately-invoked function expression?

回答1:

Sure it's possible, just load the util.js file before the rest. ALthough if I were you (seems like you're starting to have several different files in your project) I'd check out http://requirejs.org/ or some other AMD library to break up your project in modules.



回答2:

Yes, this is possible only thing is you have to include Utils.js file before calling Class.extend, so that browser should be able to find the base class.

Browser works like an interpreter, it loads scripts once it finds the script tag



回答3:

Does it have something to do with the method being wrapped in an immediately-invoked function expression?

Yes, in the moment in which the utils.js script is loaded, the method executes and returns the object Class to the global scope. From then on, the object can be used in all other files.