0

I know that this is usually used to reference data within the same object.
Are there any cases where this can reference methods inside the object, not props?
What are the pluses and minuses of doing that?

var person = {
  name: "John",
  showName() {
    return this.name;
  },
  showNameAgain() {
    return this.showName();
  }
};


console.log( person.showName() );

console.log( person.showNameAgain() );
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
Tiberiu
  • 418
  • 1
  • 3
  • 12
  • 2
    Using `this` to refer to methods is **extremely** common; it's a basic part of JavaScript programming with objects. – Pointy Jan 04 '19 at 16:35
  • 1
    The code you posted doesn't use `this` to reference any methods... it does *call* a method though... – Greg Burghardt Jan 04 '19 at 16:35
  • 1
    @GregBurghardt you can't call a method without acquiring a reference to it ... – Pointy Jan 04 '19 at 16:36
  • There are no existential programming problems, just code readability and performance issues – Mister Jojo Jan 04 '19 at 16:36
  • 3
    I think you need to read [How does the “this” keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Liam Jan 04 '19 at 16:36
  • 1
    @Pointy: I'm not clear what the OP means by "this can reference methods inside the object" then. I assumed he mean to pass or return a reference to the method rather than invoke it: `return this.showName` versus `this.showName()` – Greg Burghardt Jan 04 '19 at 16:39
  • I also don't know what "this can reference methods inside the object" is trying to say – Liam Jan 04 '19 at 16:40
  • @GregBurghardt sure; I don't really understand the issue either. It seems like a few minutes of reading almost any JavaScript tutorial about objects and inheritance would turn up lots of ordinary uses of `this`. – Pointy Jan 04 '19 at 16:40

0 Answers0