Basically, im trying to make a package that would look like this in my main project file
const package = require("package");
const newPackage = new package({
param: 'value',
otherParam: 'otherValue'
});
and then in every other project file I could use
const { someFunction } = require('package')
someFunction()
and then the SomeFunction()
function should return value
and otherValue
without needing to do
const package = require("package");
const newPackage = new package({
param: 'value',
otherParam: 'otherValue'
});
newPackage.someFunction()
in every project file.
Im not sure how to do this or if this is even possible, but would love something that would work like (or similar to) this.
While it would be possible to do this, it would involve some pretty smelly code - the package would have to have calling the constructor produce side-effects and return an unused instance. For a very slight tweak, consider instead if you could change the init code from
const package = require("package");
const newPackage = new package({
param: 'value',
otherParam: 'otherValue'
});
to something like
const { init } = require("package");
init({
param: 'value',
otherParam: 'otherValue'
});
That would be quite doable and not smelly. Put a variable in the package's scope that gets assigned to when init
is called, and return that variable when someFunction
is called.
let initObj;
module.exports = {
init(obj) {
initObj = obj;
},
someFunction() {
return initObj;
}
};
Live snippet:
const theModule = (() => { let initObj; return { init(obj) { initObj = obj; }, someFunction() { return initObj; } } })(); theModule.init({ param: 'value', otherParam: 'otherValue' }); console.log(theModule.someFunction());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.