Javascript 使用方法导出匿名函数
获取有关使用Node.js导出匿名函数的问题 此导出的预期结果:Javascript 使用方法导出匿名函数,javascript,node.js,Javascript,Node.js,获取有关使用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
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) {}
};
}
所以它有两个问题:
/index.js
导入库-这确实是正确的文件吗this
,以链接方法:如果您不喜欢当前的方法,这里有两种方法可以很好地满足您的需要: 使用实际的构造函数: 使用常规的旧
类
:
re 1)您能否澄清“无法通过date('2017-05-16 13:45')调用它”是什么意思,因为我已经对它进行了测试,可以使用该字符串调用它。它是否必须是匿名函数?它需要更多的代码才能按照您想要的方式工作,而不仅仅是使用一个类并包装它
module.exports=Date
?规范允许构造或调用Date()
。Edit Nevermind,我看到当调用它时,它返回一个字符串。
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');
// 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 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);
}