An object review (side question)


#1


https://www.codecademy.com/en/courses/objects-ii/0/1?curriculum_id=506324b3a7dffd00020bf661


I know how to pass this exercise, but I was playing with it more for better understanding and I came across a question. Why doesn't this console.log that I've added print correctly. Why does it only work when noted as console.log(this.job); Shouldn't gabby be defined by the time the function is called?


function Person(job, married) {
    this.job = job;
    this.married = married;
    console.log(gabby.job);
}

// create a "gabby" object using the Person constructor!
var gabby = new Person("student", true);


#2

When I this code.

function Person(job, married) {
    this.job = job;
    this.married = married;
    console.log(gabby.job);
}

// create a "gabby" object using the Person constructor!
var gabby = new Person("student", true);

It prints student to the console. Is this not what you were trying to achieve?


#3

For some reason I get: "TypeError: Cannot read property 'job' of undefined". Even when copying your code over mine. But again when I change it to this it works fine and displays student.

function Person(job, married) {
    this.job = job;
    this.married = married;
    console.log(this.job);
}

// create a "gabby" object using the Person constructor!
var gabby = new Person("student", true);

#4

We would never hard code an instance name in a constructor. Use the context variable, this.


#5

I understand that it is extremely bad practice, my confusion is that fact that it worked?


#6

It worked because the instance was already defined. Don't create the instance (refresh the page to clear the cache) and run it again. Should raise a exception.


#7

As always @mtf I thank you. This really confused me and I was researching trying to find out why that had worked so I could explain.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.