mardi 15 décembre 2020

Oriented Object Programming value change with conditions

Hi I begin learning Oriented Object Programming in JavaScript today.

I create an constructor object (if I understand => don't be hard I'm a beginner) called Person that take four arguments (name, age, color, gender) :

function person(name, age, color,gender) {
    this.name = name;
    this.age = age;
    this.favColor = color;
    this.sex=gender

Then I have new instances (2 instance to be precise), that are calling the four parameters.

let person1 = new person("John", 42, "green","m");
let person2 = new person("Amy", 21, "red","w")

At the end I made 1 sentence accessing the different properties/values of the person object for each instance with document.write() to output the result like this:

document.write(`<h3>${person1.name} is a ${person1.sex}, he is:${person1.age} years old and his favorite color is the "${person1.favColor.toUpperCase()}"</h3>`); 
document.write("<br>");
document.write(`<h3>${person2.name} is a ${person2.sex}, she is:${person2.age} years old and her favorite color is the "${person2.favColor.toUpperCase()}"</h3>`);

But the problem is, I wan't when the user is a woman to type just the the first letter of the word that is "w" and for a man the letter "m".

I made a condition in the object constructor but it doesn't works:

 if(person.sex=="w"){
        person.sex="woman"
    }
}

I don't know why the condition doesn't work, because it only output "w" instead of "woman".

Here the complete code:

function person(name, age, color,gender) {
    this.name = name;
    this.age = age;
    this.favColor = color;
    this.sex=gender

    if(person.sex=="w"){
        person.sex="woman"
    }
    else if(person.sex=="m"){
        person.sex="man"
    }
}

let person1 = new person("John", 42, "green","m");
let person2 = new person("Amy", 21, "red","w");

document.write(`<h3>${person1.name} is a ${person1.sex}, he is:${person1.age} years old and his favorite color is the "${person1.favColor.toUpperCase()}"</h3>`); 
document.write("<br>");
document.write(`<h3>${person2.name} is a ${person2.sex}, she is:${person2.age} years old and her favorite color is the "${person2.favColor.toUpperCase()}"</h3>`);

And here the output:

enter image description here

==============

Aucun commentaire:

Enregistrer un commentaire