[英]Export anonymous function with methods
有一個關於使用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世界,所以任何幫助將非常感謝!
謝謝你,伊戈爾
這對我來說似乎是可調用的,您使用的是哪個版本的節點? 你似乎是從./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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.