Object-oriented JavaScript for beginners

learning

(Modestas) #1

“there are a couple of problems with our bio() method — the output always includes the pronoun “He”, even if your person is female”

Hi, im trying to do the first part of this task which is to replace the pronoun based on gender. I came up with a simple solution which in my mind makes sense, but doesnt work, can someone explain why it doesnt?

function Person(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;

this.bio = function() {
var maleBio = ’ years old. He likes '
if (this.gender === “female”) {
maleBio.replace(“He”, “She”)
}
alert(this.name.first + ’ ’ + this.name.last + ’ is ’ + this.age + maleBio + this.interests[0] + ’ and ’ + this.interests[1] + ‘.’);

};
this.greeting = function() {
alert('Hi! I’m ’ + this.name.first + ‘.’);
};
}

var person1 = new Person(“Katrina”, “Ballerina”, 29, “female”, [“boxing”, “ballet”])

Thank you!


(Chris Mills) #2

Hi there!

This is a good question — the answer is that the replace() method call wasn’t working as expected. To actually update the value of the variable, you have to set the variable value to be equal to the result of the operation. Just calling replace() on the string doesn’t automatically update its value.

So just doing

maleBio.replace(“He”, “She”)

Replaces “He” with “She” in the string, but then the resulting string isn’t stored anywhere; the result is just lost in space. To get this to work, you’d have to do this:

maleBio = maleBio.replace(“He”, “She”)

I wrote the following update to the bio method, which works as expected:

this.bio = function() {
  var bio = ' years old. He likes ';
  if (this.gender === "female") {
    bio = bio.replace("He", "She");
  }
  alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + bio + this.interests[0] + ' and ' + this.interests[1] + '.');
};

BTW, I’m guessing that your confusion here might have resulted in my poor explanation in the “Useful string methods” article. Sorry about that. I’ve update this section with some better explanation: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods#Updating_parts_of_a_string


(Modestas) #3

Thanks man, i dont think its your fault i believe i already learned that but i just forgot. I can tell you care about making this the best possible learning environment, i appreciate it. Keep it up!


(Eric Shepherd) #4

Right; the important thing to remember is that JavaScript’s standard objects’ functions often don’t modify an existing object but instead return a new one, so you have to do

myString = myString.replace(“Hello”, “Goodbye”);

Eric Shepherd
Senior Technical Writer

MDN Web Docs

https://developer.mozilla.org/

Blog: https://www.bitstampede.com/

Twitter: https://www.twitter.com/sheppy


(Chris Mills) #5

Thanks! Don’t hesitate to get in touch with us if you have any more feedback or questions.