4. Can I See Your References?



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

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

// james' second job


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.


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!


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.


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