关于使用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) {}
};
}所以它有两个问题:
新的js世界,所以任何帮助都将非常感谢!
谢谢你,伊戈尔
发布于 2018-02-06 16:37:13
./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);
}https://stackoverflow.com/questions/48647160
复制相似问题