4. Can I See Your References?


#1


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


This code works; it prints what it's supposed to to the console but codecademy says it is wrong. Why do you need to use "this"?


var james = {
    job: "programmer",
    married: false,
    sayJob: function(job) {
       console.log ("Hi, I work as a " + job)
        
    }
};

// james' first job
james.sayJob();

// change james' job to "super programmer" here
james.sayJob("super programmer");

// james' second job
james.sayJob();


#2

In the above, job is a global variable, not an ownProperty. It will raise an exception since job is undefined. this identifies the object instance's own properties. Inside the object methods, it is used to reference those properties.

console.log(james.hasOwnProperty('job'));    // true

console.log(james.job);    // programmer

console.log ("Hi, I work as a " + this.job)

is the equivalent of (and much more convenient)

console.log ("Hi, I work as a " + james.job)

We wouldn't write the last line in our programs since it is not dynamic, but static. We could never clone this method to a new object. Writing this makes our method dynamic and shareable.


#3

Hey, instead of: console.log ("Hi, I work as a " + job), you should put console.log ("Hi, I work as a " + " " + this.job).
Also, on line 14, it should say james.job("super programmer"); instead of james.sayJob("super programmer");
I hope this helped you!


#4

Just wanted to drop a "thanks" here for that little explanation on the difference between "james.job" and "this.job". I was playing around after doing the exercise and saw that "james.job" worked just fine instead of using "this.job". Until your reply I wasn't exactly sure what the benefit of using this.job was. Now I do. Appreciate that.


#5

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