Lessson 15/4 query about when to use .this


#1

Hi I'm just trying to get my head around the this. function. In the example in the exercise it has james.job referred to as this.job in the codeblock of the function. I know this is a limited example but if the function local in scope within the james object would it not make more sense to use james.job in the console.log text. It works either way but I'm wondering if there is a reason for the .this that I don't know about, and if there is a more technically correct way of coding in this situation.

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

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

// change james' job to "super programmer" here
james.job = "super programmer"

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

Thanks


#2

@cmdrcrunk,
To get some background knowledge:

++ this explained ++

Reference::

google search
== the Book ==
javascript this site:developer.mozilla.org
= https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

== discussions /opinions ==
javascript this explained site:stackoverflow.com
= http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work
= https://www.codecademy.com/forum_questions/55f03d4b93767651db0005b3

Have a read through
= http://stackoverflow.com/questions/4354418/var-vs-this-vs-constructor-parameter-variables
and
= http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/


#3

Thanks. I've just finished the course (took well longer than 10 hours but I've made careful notes throughout).
I'm also reading Java for Dummies and learn JavaScript in 24 hours. Thanks for the links I will check them out. I guess I'm trying to learn via shortcuts on this message board, which I know is wrong. It's a long road ahead and one step at a time I guess.

Thanks for the reply :smile: