Object-oriented_JS
declaring an object literal, and using a constructor function
by Rafa Ola
JavaScript
function createNewPerson(name){
var obj = {};
obj.name = name;
obj.greeting = function(){
alert('Hi! I\'m ' + this.name + '.');
document.write('Hi! I\'m ' + this.name + '.');
};
return obj;
}
var misi = createNewPerson('Oluwamisi');
misi.name;
misi.greeting();
//Fortunately, JavaScript provides us with a handy shortcut, in the form of constructor functions —
// Replace your previous function with the following
function Person(first, last,age,gender,interests){
this.name = {
'first': first,
'last': last
};
this.age = age;
this.gender = gender;
this.interests = interests
this.bio = function(){
let string = '<p>'+ this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. '+ '</p>';
let pronoun;
if(this.gender === 'male' || this.gender === 'Male' || this.gender === 'm' || this.gender === 'M') {
pronoun = 'He likes ';
} else if(this.gender === 'female' || this.gender === 'Female' || this.gender === 'f' || this.gender === 'F') {
pronoun = 'She likes ';
} else {
pronoun = 'They like ';
}
string += pronoun;
if(this.interests.length === 1) {
string += this.interests[0] + '.';
} else if(this.interests.length === 2) {
string += this.interests[0] + ' and ' + this.interests[1] + '.';
} else {
// if there are more than 2 interests, we loop through them
// all, adding each one to the main string followed by a comma,
// except for the last one, which needs an and & a full stop
for(var i = 0; i < this.interests.length; i++) {
if(i === this.interests.length - 1) {
string += 'and ' + this.interests[i] + '.';
} else {
string += this.interests[i] + ', ';
}
}
}
// finally, with the string built, we alert() it
document.write(string);
};
this.greeting =...