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
Jochem
Jochem2mo ago
Cause methods and properties aren't that different. They're both references in Javascript
glutonium
glutonium2mo ago
methods also can refer to the property of the current instance in them , like for example
public printName() {
console.log(this.name);
}
public printName() {
console.log(this.name);
}
so ig maybe that's also why u need to refer to the methods with this as well
Faker
FakerOP2mo ago
yeah but the method won't be the same for all the instances ? so why explicitly make use of the this keyword
Jochem
Jochem2mo ago
because it's a part of the instance still
Faker
FakerOP2mo ago
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 ?
Jochem
Jochem2mo ago
no, you'd usually define a method in the main scope of the class, where you'd just write them like this
class MyClass {
someMethod() {
//...
}
}
class MyClass {
someMethod() {
//...
}
}
or this in an object
const obj = {
a() {
//...
}
}
const obj = {
a() {
//...
}
}
you'd refer to them inside the object/instance by using this.someMethod or this.a afaik though
Faker
FakerOP2mo ago
yeah I see, thanks !
Want results from more Discord servers?
Add your server