2016-04-15 38 views
0

我試圖創建一個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導入並用作側的流星(1.3)的幫手構造爲一個Blaze模板。

但是,我得到的回覆爲validator.js:33 Uncaught TypeError: this.validateRegEx is not a function。我正在努力弄清楚爲什麼。誰能幫忙?

+3

調用'.validate()'到底是多少?問題是*可能*這個''不是對'FormValidator'實例的引用。如果(例如)'validate'函數引用被用作沒有包裝的事件處理程序,就會發生這種情況。 – Pointy

+1

完成。謝謝! – Hans

回答

0

好的,在Pointy的評論的幫助下,我自己想到了這個問題。以下解決方案

這是我用來做打電話的validate(流星火焰模板中):

我初始化的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中處理這個問題時仍然感到非常困惑。