I am new to Javascript and object-oriented programming in general. I would like to know if I am following the best practices when writing JS OOP code.
Here I made a class called _name and gave it some properties as well as an object this.details. Then I use prototyping to create methods for the class.
//define _name class (I use _ to easily recognize classes)
function _name () {
this.firstName = '';
this.lastName = '';
this.middleName = '';
this.details = {
eyeColor: '',
hairColor: ''
}
}
//begin _name methods
_name.prototype.getFullName = function() {
return this.firstName + ' ' + this.middleName + ' ' + this.lastName;
}
_name.prototype.setFirstName = function(firstName) {
if ($.trim(firstName).length && typeof firstName != 'not_defined') {
this.firstName = firstName;
} else {
alert('Please enter a valid first name.');
}
}
_name.prototype.setLastName = function(lastName) {
if ($.trim(lastName).length && typeof lastName != 'not_defined') {
this.lastName = lastName;
} else {
alert('Please enter a valid last name.');
}
}
_name.prototype.setMiddleName = function(middleName) {
if ($.trim(middleName).length && typeof middleName != 'not_defined') {
this.middleName = middleName;
} else {
alert('Please enter a valid middle name.');
}
}
_name.prototype.setHairColor = function(hairColor) {
this.details.hairColor = hairColor;
}
_name.prototype.setEyeColor = function(eyeColor) {
this.details.eyeColor = eyeColor;
}
//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);