Javascript对象看不到内部函数

Javascript object does not see internal function

本文关键字:内部函数 看不到 对象 Javascript      更新时间:2023-09-26

我正在尝试创建这样一个javascript原型风格的类。。。

const _FormValidator = function(fieldDefinition){
  // check the regEx is actually a regEx
  const regEx = fieldDefinition.regEx;
  const regExType = Object.prototype.toString.call(regEx);
  if (regExType === '[object RegExp]'){
    this.regEx = regEx;
  }
  // just make the mandatory property true or false.
  this.isMandatory = false;
  if (fieldDefinition.mandatory){
    self.isMandatory = true;
  }
}
_FormValidator.prototype.validateRegEx = function(value){
  const regEx = this.regEx;
  if (!regEx){
    return true;
  }
  return regEx.test(value);
}
_FormValidator.prototype.validateMandatory = function(value){
  if (!value){
    return !this.mandatory;
  }
  return true;
}
_FormValidator.prototype.validate = function(value){
  const validRegEx = this.validateRegEx(value);
  const validMandatory = this.validateMandatory(value);
  return validRegEx && validMandatory;
}
export const FormValidator = _FormValidator;

FormValidator被导入并用作Blaze模板的Meteor(1.3)助手中的构造函数。

然而,我得到了响应validator.js:33 Uncaught TypeError: this.validateRegEx is not a function。我很难弄清楚为什么。有人能帮忙吗?

好吧,在Pointy评论的帮助下,我自己解决了这个问题。解决方案如下。

这就是我过去所做的调用validate(在Meteor Blaze模板中):

我在onCreated方法中初始化验证器,如下所示:

  const validator = new FormValidator(instance.data.field);
  instance.validate = validator.validate;

然后我把它叫做instance.validate(value)

我现在已经将其更改为:

  const validator = new FormValidator(instance.data.field);
  instance.validator = validator;

并将其称为解决问题的instance.validator.validate(value)。很抱歉,在javascript中处理这个问题时,我仍然感到非常困惑。