4. A few questions about "this"

javascript

#1

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

james.job = "Janitor";

What happens if I changed it to job? let's assume that there is no variables name job other than the object.

And since I said this.job, would it print out the new job (Janitor) or both?


#2

Could you please clarify it? if you mean the james object, then that would not be a problem. This code:

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

job.job = "Janitor";

would work fine. If you think it should not work in some line, please tell which line it shouldn't work.

Thanks!


#3

@netace24408

  1. Well, like I tried it in the console and it says

I guess your job variable is not defined because job can be a variable you created outside the james object. This is why it will return no defined because you haven't created this variable. In this case, using this will refer to the job variable in the james object.

2.It will print Janitor since you assigned a new value to job variable in james object. This means when you assign this value, it will never be equal to the value before unless you set it back to its original value.