我不明白为什么我会在element is not exported
行的以下JavaScript中收到WebStorm IDE中的this.errors
。
function FooBar(userId, email) {
if (!util.isString(userId) || !userId.length) {
throw Error('FooBar(): requires a non-empty userId:String');
}
if (this instanceof FooBar) {
this.id = generateId();
this.userId = userId;
this.email = email;
this.curStep = WORKER_STEPS[0];
this.completed = false;
this.failed = false;
this.createDate = new Date();
this.errors = {};
for (let step of WORKER_STEPS) {
this.errors[step] = 0;
}
} else {
return new FooBar(userId, email);
}
}
答案 0 :(得分:1)
我知道我可以获得许多投票,因为它超出了问题的范围。
但现在是时候切换到ES6了 所以我会给你更好的解决方案(:
1)启用EcmaScript 6支持:
2)切换到class
以避免使用function
将它添加到js文件的顶部,它将使nodejs解释器提醒内存韭菜或不必要的变量定义等等。
/* jshint strict: true */
'use strict';
这是你的FooBar
:
const
_ = require('lodash');
class Entity {
hasError() {
return !_.isEmpty(this.errors);
}
addError(step, error) {
this.errors[step] = error;
}
getErrors() {
return this.errors;
}
}
class FooBar extends Entity {
constructor(userId, email, steps = []) {
if (_.isEmpty(userId) || !_.isString(userId))
throw Error('FooBar(): requires a non-empty userId:String');
this.id = generateId();
this.userId = userId;
this.email = email;
this.curStep = _.first(steps);
this.completed = false;
this.failed = false;
this.createDate = new Date();
this.errors = {};
}
}
用法:
let
fooBar = new FooBar(
'1f049de1-b592-4f17-9a7d-3f2097477b23',
'somebody@gmail.com',
WORKER_STEPS);
fooBar.addError(0, "Something happen"); // or fooBarInstance.addError("Somewhere", "Something happen");
if(fooBar.hasError()) {
console.error(fooBarInstance.getErrors());
}