从内部函数更新对象属性

时间:2020-05-22 10:39:41

标签: javascript

我正在尝试在它设置的validations内的函数中更新isValid to false中的值,但是没有在函数外更新validations的值,我该怎么做?

export let validations = {
    validate: null,
    isValid: true,
    validationMessage: ''
};

function validateInput(value) {
    if (value == null || value.length === 0) {
        const update = {...validations, isValid: false}
        {console.log(bla)}
    return update
}

2 个答案:

答案 0 :(得分:2)

您尝试过吗:

export let validations = {
    validate: null,
    isValid: true,
    validationMessage: ''
};

function validateInput(value) {
    if (value == null || value.length === 0) {
      validations.isValid = false
    }
}

答案 1 :(得分:1)

是否要保留实际的验证对象,并且validateInput函数应返回其验证结果

export let validations = {
    validate: null,
    isValid: true,
    validationMessage: ''
};

function validateInput(value) {
    const update = {...validations};
    if (value == null || value.length === 0) {
        update.isValid = false;
    }
    return update;
}

或类似的

export let validations = {
    validate: function(value){
     if (value == null || value.length === 0) {
        this.isValid = false;
        this.validationMessage = 'No value'
    }},
    reset: function(){
        this.isValid = true;
        this.validationMessage = '';
    },
    isValid: true,
    validationMessage: ''
};