Got a question about exporting anonymous function using Node.js What expected in result from this export:
var date = require('./index.js');
var time = date('2017-05-16 13:45')
.add(24, 'hours')
.subtract(1, 'months')
.add(3, 'days')
.add(15, 'minutes');
In index.js i've tried to export anonymous function like
module.exports = function(date){
return {
exports: function(date){},
add: function (value, type) {},
subtract: function (value, type) {}
};
}
So got 2 problems with it:
New to js world, so any help would be very appreciated!
Thanks in advance, Igor
This appears callable for me, which version of node are you using? You seem to be importing your library from ./index.js
- is that definitely the right file?
You'll need to return this
in order to chain methods:
test.js
var date = require('./index.js');
var time = date('2017-05-16 13:45')
.add(24, 'hours')
.subtract(1, 'months')
.add(3, 'days')
.add(15, 'minutes');
index.js:
// NB: I've named the outer variable `_data` since you can
// access it from within the other functions (closure)
module.exports = function(_date) {
return {
exports: function(date) {
// do things here
return this;
},
add: function(value, type) {
// do things here
return this;
},
subtract: function(value, type) {
// do things here
return this;
}
};
}
In case you're not attached to your current approach, here are two alternatives which should work fine for your purposes:
with an actual constructor function:
// the benefit here is that your methods don't get recreated for every
// instance of the class
function Date(_date) {
this.date = _date;
}
Date.prototype = Object.assign(Date.prototype, {
exports: function(date) {
// do things here
console.log(date, this.date);
return this;
},
add: function(value, type) {
return this;
},
subtract: function(value, type) {
return this;
}
})
// this function isn't strictly necessary, just here to
// maintain compatibility with your original code
module.exports = function(date) {
return new Date(date);
}
with a regular old class
:
class Date {
constructor(date) {
this.date = date;
}
exports(date) {
return this;
}
add(value, type) {
return this;
}
subtract(value, type) {
return this;
}
}
// this function isn't strictly necessary, just here to
// maintain compatibility with your original code
module.exports = function (date) {
return new Date(date);
}
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.