Objects - .this Scope


#1

Hi,
So i’m continuing on with the JS course, and i think i’m doing okay so far. I do have a question relating to objects and the this keyword.

In This lesson , we learn that

Now, from this codesnippet (warning: it’s paraphrased from the rest of that lesson), it looks like the if statement is a direct child of the openRestaurant function. Wouldn’t that be accessible at a block scope level? Or local (to the full object, and the function)?

Some pointers on this would be appreciated (as per the lesson though, I understand what this is doing.

Thanks guys!


#2

this article explains it really nicely:

scope (or rather context) in objects is different then regular function you learned so far.

JS makes grasping the concept of this even more difficult, given it can refer to the window object (the browser window)

Context is always the value of the this keyword which is a reference to the object that “owns” the currently executing code. in this case person


#3

This is a difficult concept to get a grasp of huh? :laughing:


#4

Yep, and JS isn’t helping (given its implemented it very differently from other languages, this has to do with JS being used in the browser)


#5

nod as far as i can tell, you mean something along the lines of things having their own scope and context within objects, then block scope, local, global, and eventually that all gets a spanner thrown in the works when you take into account the DOM’s own scope rules?


#6

that sounds about right.

But currently you are not yet working with the DOM, so you won’t have to worry about it yet

but that JS has to work with DOM has influence on how the language is build.


#7

I’ve done a little DOM manipulation outside of codeacademy, not much though.

Ermm. I feel like I should give a summary of some sort so others may benefit if they come look at this question.

Short Answer It’s slightly more convoluted than just local/global scopes. Just go with it for now.
Longer Answer Understanding Scope and Context in Javascript As posted above, but may be a difficult read for beginner types.


#8

the very short version, to access properties (this includes methods) within a method we need this keyword. Given this refers to the current object

Methods can call methods, just like function can call functions


#9

Perfect, that hugely simplifies it for now.
Was fun spit ballin’ with you, stetim. Look forward to buggin’ you again later lol! Thanks :slight_smile:


#10

Yep, you just have to let go of the scope what you learned so far, for objects its different again

but its not accurate, you can also construct the object in such a way that this refers to the window object (of your browser), which is the default scope, uhm… context i think, which you can see if you run this code:

console.log(this);

which gives [object Window]


#11

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