0

我开始在 JS 中学习 OOP,我遇到了这个问题,当返回 false时我alert()不会触发。validateString我尝试personOne.setFirstName('');alert()不会触发。

//define Name class 
function Name () {
    this.firstName = '';
    this.lastName = '';
    this.middleName = '';
    this.details = {
        eyeColor: '',
        hairColor: ''
    }
};

var validateString = function(p) {
    return typeof p != "undefined" && $.trim(p).length;
};

//begin Name methods
Name.prototype.getFullName = function() {
    return this.firstName + ' ' + this.middleName + ' ' + this.lastName;
};
Name.prototype.setFirstName = function(p) {
    if (validateString) {
        this.firstName = p;
    } else {
        alert('Please enter a valid first name.');
    }
};
Name.prototype.setLastName = function(p) {
    if (validateString) {
        this.lastName = p;
    } else {
        alert('Please enter a valid last name.');
    }
};
Name.prototype.setMiddleName = function(p) {
    if (validateString) {
        this.middleName = p;
    } else {
        alert('Please enter a valid middle name.');
    }
};
Name.prototype.setHairColor = function(p) {
    this.details.hairColor = p;
};
Name.prototype.setEyeColor = function(p) {
    this.details.eyeColor = p;
};

//end Name methods

var personOne = new Name();
personOne.setFirstName('John');
personOne.setLastName('Doe');
personOne.setMiddleName('Barry');
personOne.setEyeColor('Brown');
personOne.setHairColor('Black');
document.write(personOne.getFullName());
document.write(personOne.details.eyeColor);
document.write(personOne.details.hairColor);
4

2 回答 2

2

您需要将参数传递给validateString.

if (validateString(p)) {
  //etc
}

编辑: ...而且,正如@potench 所提到的,该if语句被评估的原因true是因为:

if (myFunc) {
  //blah
}

意思是“如果myFunc作为定义的变量存在”。在这种情况下,它与if (3)or相同if (true)

于 2012-06-29T05:36:27.730 回答
0

validateString在这种情况下你不需要。考虑

Name.prototype.setFirstName = function(p) {
  this.firstName = p || alert('please enter a first name');
}

这称为短路布尔值。如果未提供参数,或者参数为空字符串,则会触发警报并this.firstName will be undefined. If you need to check te length of使用 p`,使用:

Name.prototype.setFirstName = function(p) {
  this.firstName = (p && p.trim().length) || alert('please enter a first name');
}
于 2012-06-29T05:52:42.867 回答