Javascript`typeof`验证问题

时间:2012-06-29 05:34:36

标签: javascript oop

我开始在JS中学习OOP,我遇到了这个问题,alert()validateString返回false时不会触发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); 没有触发。

{{1}}

2 个答案:

答案 0 :(得分:2)

您需要将参数传递给validateString

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

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

if (myFunc) {
  //blah
}

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

答案 1 :(得分:0)

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

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

这称为short circuit boolean。如果未提供参数,或者参数为空字符串,则会触发警报并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');
}