Why do I need l to put this.job instead of just job in function


#1


In the function, sayJob(), I tried to reference job without the this keyword and it didn't work. I'm confused as to how this works in this literal case. I think I understand the way it works in a constructor; that it will refer to the object created.

Thanks,
Leo

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


#2

this.job refers to the job property of the class/object whereas job alone refers to the variable passed into the function using the name job.

This is more clearly shown if the exercise is rewritten like so:

var object = {
    job: "programmer",
    sayJob: function(greeting) {
        return greeting + ", I work as a " + this.job + ".";
    }
};

console.log(object.sayJob("Hello"));

As you can see, greeting is now a function argument, and can be called without the preceeding this. whereas this.job still references the job property of the object "object".


#3

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