'this.variable'不会改变?

时间:2014-10-28 10:02:31

标签: javascript

我从下面的函数创建了一堆新对象。然后,在循环中,我遍历每个循环并调用方法toggleValid()和toggleErrMsg()。在toggleErrMsg()中,如果它是假的,它应该将object.errMsgStatus的值更改为true,但它不会。为什么呢?

  function InputField(field, cssTarget, value, errMsg, validator) {
    var self = this;
    this.field = field,
    this.cssTarget = cssTarget,
    this.value = value,
    this.valid = false,
    this.errMsg = errMsg,
    this.errMsgStatus = false,
    this.validator = validator,
    this.toggleErrMsg = function() {
        if(self.valid === false && self.errMsgStatus === false) {
            self.errMsgStatus = true;
            renderValidationError(self, false);
        } else {
            self.errMsgStatus = false;
            renderValidationError(self, true);
        }
    }
    this.toggleValid = function() {
        self.validator();
        if(!self.valid) {
            self.cssTarget().addClass("inputInvalid");
        } else {
            self.cssTarget().removeClass("inputInvalid");
        }

    }
}

2 个答案:

答案 0 :(得分:0)

这可能与初始化输入字段的方式有关。 由于尚未提供任何代码,您可能正在进行

var inputField = InputField();

虽然它应该是

var inputField = new InputField();

答案 1 :(得分:-2)

  function InputField(field, cssTarget, value, errMsg, validator) {
    var self = this;
    self.field = field,
    self.cssTarget = cssTarget,
    self.value = value,
    self.valid = false,
    self.errMsg = errMsg,
    self.errMsgStatus = false,
    self.validator = validator,
    this.toggleErrMsg = function() {
        if(self.valid === false && self.errMsgStatus === false) {
            self.errMsgStatus = true;
            renderValidationError(self, false);
        } else {
            self.errMsgStatus = false;
            renderValidationError(self, true);
        }
    }
    this.toggleValid = function() {
        self.validator();
        if(!self.valid) {
            self.cssTarget().addClass("inputInvalid");
        } else {
            self.cssTarget().removeClass("inputInvalid");
        }

    }
}