Reputation: 663
I'm writing a JavaScript closure that contains classes and looks a bit like this:
// myClosure.js
var myClosure = (function() {
class myClass {
constructor(val) {
this.myValue = val;
}
myFunc() {
console.log("myClass says: " + this.myValue);
}
}
this.myClass = myClass;
});
I'd like to 'import' this closure into another JavaScript file and instantiate a myClass
. I tried this:
// myApp.js
$.getScript('myModule.js', function(myClosure) {
var myClassInstance = new myClosure.myClass(7);
}
but I get an error claiming that myClosure.myClass
is not a constructor.
Can someone please point to a simple example, or a better way of doing this altogether?
Upvotes: 0
Views: 134
Reputation: 94
you need to export this function first to include it in another javascript file.
if you are using node simply use module.exports = function name or for es6 you can use export default
and in another file simply import it
Upvotes: 0
Reputation: 24191
Couple of things, myClosure returns nothing, so you will never be able to access it. In your example you could just return this.
Next, you have not executed the closure, you can do this by putting ()
at then end to make it into an IFFE..
Below is an example.
// myClosure.js
var myClosure = (function() {
class myClass {
constructor(val) {
this.myValue = val;
}
myFunc() {
console.log("myClass says: " + this.myValue);
}
}
this.myClass = myClass;
return this; //add this
}()); //and <- () that.
var myClassInstance = new myClosure.myClass(7);
myClassInstance.myFunc();
Upvotes: 1
Reputation: 943579
this
doesn't work anything like thatmyClosure
is a function which doesn't create a closuregetScript
is a string containing the script. It isn't a value from the script.To get values from it, you need to access a global.
Typically, if you were using jQuery.getScript, it would look something like this:
// myModule.js
class myClass {
// etc
}
// main.js
$.getScript('myModule.js', function () {
const myInstance = new myClass(7);
});
Modern code would tend towards using ES6 modules:
// myModule.js
class myClass {
// etc
}
export default myClass;
// main.js
import myClass from "./myModule.js";
const myInstance = new myClass(7);
// HTML
<script type="module" src="main.js"></script>
… although that sacrifices Internet Explorer support, in which cases you would want to look at using a bundler tool like Webpack.
Upvotes: 0