我开始在 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);