我正在尝试编写我的第一个 NodeJS 模块,但我无法理解一些概念。
这是我目前拥有的代码(genexer 计数器/生成器):
"use strict";
var ret = require('ret');
module.exports = function (regex) {
if (Object.prototype.toString.call(regex) === '[object RegExp]') {
regex = regex.source;
}
else if (typeof regex !== 'string') {
regex = String(regex);
}
try {
var tokens = ret(regex);
}
catch (exception) {
return false;
}
return {
charset: '',
reference: [],
count: function (token) {
var result = 0;
if ((token.type === ret.types.ROOT) || (token.type === ret.types.GROUP)) {
if (token.hasOwnProperty('stack') === true) {
result = 1;
token.stack.forEach(function (node) {
result *= count(node);
});
}
else if (token.hasOwnProperty('options') === true) {
var options = [];
token.options.forEach(function (stack, i) {
options[i] = 1;
stack.forEach(function (node) {
options[i] *= count(node);
});
});
options.forEach(function (option) {
result += option;
});
}
if ((token.type === ret.types.GROUP) && (token.remember === true)) {
reference.push(token);
}
}
else if (token.type === ret.types.POSITION) {
}
else if (token.type === ret.types.SET) {
token.set.forEach(function (node) {
if (token.not === true) {
if ((node.type === ret.types.CHAR) && (node.value === 10)) {
}
}
result += count(node);
});
}
else if (token.type === ret.types.RANGE) {
result = (token.to - token.from + 1);
}
else if (token.type === ret.types.REPETITION) {
if (isFinite(token.max) !== true) {
return Infinity;
}
token.value = count(token.value);
for (var i = token.min; i <= token.max; ++i) {
result += Math.pow(token.value, i);
}
}
else if (token.type === ret.types.REFERENCE) {
if (reference.hasOwnProperty(token.value - 1) === true) {
result = 1;
}
}
else if (token.type === ret.types.CHAR) {
result = 1;
}
return result;
}(tokens),
generate: function () {
return false;
},
};
};
问题:
- 我是否在第一次迭代时正确地调用了
count
?count: function (token) {}(tokens)
? - 如何递归调用
count
方法?我收到“ReferenceError:计数未定义” - 这是使用多种方法定义小模块的正确(或最佳实践)方法吗?
请原谅我没有发布 3 个不同的问题,但我还不是很熟悉所有的术语。
最佳答案
- 立即调用闭包的约定是
count: (function(args) {return function() {}})(args)
但您的方式也适用于所有环境。 - 你不能,因为不幸的是 count 是一个闭包——见 3。
- 如果您想在模块内部使用模块上的方法,我会在 return 语句之外声明模块。如果你想要一个很好的例子,请参阅 underscore/
lodash源代码。
所以你可以使用像下面的框架这样的声明来定义你的模块
module.exports = function (regex) {
//...
var count = function(tokens) {
//...
return function() {
//...
var ret *= count(node);
return ret;
}
}
var mymod = {
count: count(tokens)
//...
};
//...
return mymod;
};
关于javascript - NodeJS模块开发的疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20408044/