Understanding the "this" keyword for objects in JavaScript
Hello guys, can someone explain why it is important to use the "this" keyword here, what would happen if we omit it please.
Also, I notice that when we create a class, for e.g. say
class Person {. . .}
, in this case, I don't remember we would have use the keyword this. I know that the this keyword is use to reference the current object but in the example below, don't we have a single object? So can't we omit the "this" keyword?
8 Replies
If you just wrote
name[0]
, it would look for name
in the current context, which doesn't include the other members of the object, so name
would be undefined
.
Why doesn't the current context include the other members of an object? Well, one situation that comes to mind is initialization:
If the varA
member were visible in the constructor scope, it would be "shadowed" (i.e. overwritten) by the varA
argument to the constructor.
Just in general, if all the members of an object were inserted into the namespace of the methods in that object you'd run the risk of altering the behavior of a method unexpectedly when you define a new property. Using this
makes it explicit.
You could also write person.name[0]
in this situation.
Also, as a point of syntax, you would usually write member functions as bio() {โฆ}
rather than bio: function() {โฆ}
.the
this
points to the current instance of the current object
if there's no object, it points to window
, in browsersCan you please explain what you mean by
current context
please.... I came across this word but didn't really understand how it worksThe instance of an object is the thing the code actually creates and uses. This is important in a constructor or method because you need a way to refer to the object your code created when it's running. An analogy would be that you make a generic blueprint or "design" of an object (like a person) and then when you actually create the object in the running code, you have an actual product (an instance) of that blueprint (object). Here's another example: https://www.w3schools.com/js/js_object_definition.asp
The "context" is the variables that are in scope at any point in time.
like context refers to global or local scope ?
Yeah, anything that is within scope, local or global, is in the current context.
yep I see, ty !