this keyword used on properties and methods when creating a new object in JavaScript
Hello guys, I just read that the purpose of the this keyword is to refer to the current object being executed... so writing something like this.name = name means that on that object particular being refered, we want to assign the name to it. This makes sense when we want to use a property but why should methods also have the this keyword?
7 Replies
Cause methods and properties aren't that different. They're both references in Javascript
methods also can refer to the property of the current instance in them , like for example
so ig maybe that's also why u need to refer to the methods with this as well
yeah but the method won't be the same for all the instances ? so why explicitly make use of the this keyword
because it's a part of the instance still
yeah I see, so every time I need to define a new method, I should always use the this keyword ? If ever I forgot to do so, will I get any sort of error ?
no, you'd usually define a method in the main scope of the class, where you'd just write them like this
or this in an object
you'd refer to them inside the object/instance by using
this.someMethod
or this.a
afaik thoughyeah I see, thanks !