1

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.

3
  • 5
    In personGreeting, the this keyword isn't referring to your p object (that's the person parameter since you passed p as an argument, which you never use in that function). Commented Apr 21, 2014 at 18:23
  • 2
    The way constructors (and, more generally, objects and inheritance) work in JavaScript is vastly different from how those things work in C#. Commented Apr 21, 2014 at 18:26
  • I think you need to rethink your personGreeting method. You're either going to wind up with it having a useless parameter (person) if you use this, or you're going to use person, 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 a person parameter would be if it made use of both the object that contained it and the value that was passed to it. Commented Apr 21, 2014 at 18:35

1 Answer 1

2

You are not doing anything with the passed parameter. Since you are utilizing this only the variables that are within your constructor are being called.

You COULD do person.personFullName(); and that would mean that the parameters member personFullName() would be called and not your constructors.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.