0

In the following function, with a method inside of it called newlastname :

function person(firstname,lastname,age,eyecolor)
{
  this.firstname=firstname;
  this.lastname=lastname;
  this.age=age;
  this.eyecolor=eyecolor;

  this.newlastname=newlastname;
}


function newlastname(new_lastname)
{
  this.lastname=new_lastname;
}

In the line this.newlastname=newlastname; what is happening? What does the first newlastname refer to? I appreciate any tips or advice.

2 Answers 2

2

In this line of code:

this.newlastname=newlastname;

The first newlastname is a property on the person object.

The second newlastname is a reference to the newlastname() function.

So, when you do this:

this.newlastname=newlastname;   

you are storing a reference to that function in a property of the person object. That would allow the following code to work:

var p = new person("Ted", "Smith", 31, "blonde");
p.newlastname("Bundy");

When you execute p.newlastname("Bundy");, it will look for a property on the person object called newlastname. When it finds that property, it will execute that function and pass it "Bundy" and set this to be the particular person object.

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

1 Comment

Awesome - it clicked now! Thank You very Much!
1

When you do this.x = x inside of an function (all functions are objects), the first x becomes a property of the object. So you can do this.x anywhere inside the object to access its value. example -

    function test (x)
    {
        this.x = x + 2; // the first x is an property of test. the second is the passed argument
        return this.x;
   }

   console.log(test(2)); // 4

you can also do the following to check all the properties and methods of test

console.log(new test(2));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.