有关于使用Node.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中,我试图导出像
这样的匿名函数module.exports = function(date){
return {
exports: function(date){},
add: function (value, type) {},
subtract: function (value, type) {}
};
}
因此遇到了2个问题:
js世界的新手,所以任何帮助都会非常感激!
提前致谢, 伊戈尔
答案 0 :(得分:3)
这对我来说似乎是可调用的,您使用的是哪个版本的节点?您似乎是从./index.js
导入您的库 - 这绝对是正确的文件吗?
您需要返回this
才能链接方法:
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;
}
};
}
如果您不依附于当前的方法,这里有两个替代方案可以正常用于您的目的:
带有实际构造函数的:
// 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);
}
使用常规旧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);
}