I am currently learning javascript and I attempted to make a Person
class (note - this was part of a practice exercise, so some of the design decisions may have been due to the requirements).
Specifically, I am looking for feedback on:
Usage of prototypes (i.e. from my understanding, prototype should be used when the particular behaviour/property is shared with all objects. This means there is only 1 instance of the function (e.g.)
getFullName()
which is shared across all objects, whereas the propertiesfullName
,firstName
andlastName
which are declared directly in the Person function, thus a new unique copy will be created in every instance.Usage of undefined (i.e. exercise required us to initially have
obj.firstName
to be equal to undefined. But does it make more sense to have these properties equal to undefined, or to have it equal to null, or to equal an empty string (like "").Usage of this (am I generally correct in the usage of this? Particularly when prototypes are used)
var Person = function(firstAndLast) {
this.fullName = firstAndLast;
this.firstName = undefined;
this.lastName = undefined;
};
Person.prototype.setFullName = function(firstAndLast){
this.fullName = firstAndLast;
};
Person.prototype.setFirstName = function(first){
this.firstName = first;
};
Person.prototype.setLastName = function(last){
this.lastName = last;
};
Person.prototype.getFullName = function(){
return this.fullName;
};
Person.prototype.getFirstName = function(){
//exercise required a default firstName to be set, only if this function was called
if(this.firstName === undefined){
this.firstName = this.defaultFirst();
}
return this.firstName;
};
Person.prototype.getLastName = function(){
//exercise required a default lastName to be set, only if this function was called
if(this.lastName === undefined){
this.lastName = this.defaultLast();
}
return this.lastName;
};
Person.prototype.defaultFirst = function(){
var first = "";
for(var i=0;i<this.fullName.length; i++){
if(this.fullName[i] !== " "){
first += this.fullName[i];
}else{
break;
}
}
return first;
};
Person.prototype.defaultLast = function(){
var last = "";
for(var i=this.fullName.length-1; i>0; i--){
if(this.fullName[i] !== " "){
last += this.fullName[i];
}else{
break;
}
}
return last.split("").reverse().join("");
};