Javascript对象没有看到内部函数

时间:2016-04-15 13:40:52

标签: javascript

我试图像这样创建一个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。我正在努力弄清楚原因。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

好的,在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中处理这个问题时仍然会感到非常困惑。