I have a question in respect of the js constructor function. I have the following code:
var PersonConstructorFunction = function (firstName, lastname, gender) {
this.personFirstName = firstName;
this.personLastName = lastname;
this.personGender = gender;
this.personFullName = function () {
return this.personFirstName + " " + this.personLastName;
};
this.personGreeting = function (person) {
if (this.personGender == "male") {
return "Hello Mr." + this.personFullName();
}
else if (this.personGender == "female") {
return "Hello Mrs." + this.personFullName();
}
else {
return "Hello There!";
}
};
};
var p = new PersonConstructorFunction("Donald", "Duck", "male");
p2 = new PersonConstructorFunction("Lola", "Bunney", "female");
document.write(p2.personGreeting(p2) + " ");
The result is quite obvious - --Hello Mrs. Lola Bunney--
The question is: There are two equivalent objects p and p2 with the same number of properties and methods. I can't understand the following behaviour when I call the personGreeting method of one object and pass the second object as the argument:
**document.write(p2.personGreeting(p) + " ");**
in this case I get --Hello Mrs. Lola Bunney-- but what about the p object that is passed as the argument?
personGreeting gets the person object, determines their gender and bsed on the result shows appropriate greetings.
Resently I learned C# and constructors there works similarly I guess.
personGreeting, thethiskeyword isn't referring to yourpobject (that's thepersonparameter since you passedpas an argument, which you never use in that function).personGreetingmethod. You're either going to wind up with it having a useless parameter (person) if you usethis, or you're going to useperson, in which case it makes no sense as a member method of the object. The only way it would make sense as a member method with apersonparameter would be if it made use of both the object that contained it and the value that was passed to it.