-1

if I remove the ";" after let self = this; then it does not work

let obj = {
  name: 'john',
  getInfo: function() {
    let self = this;
    (function() {
      console.log(self.name)
    }())

  }
}
obj.getInfo();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Alex Lai
  • 53
  • 6
  • Seems a bit pointless, why not just use `console.log(this.name)` as the only line of the `getInfo` function? – CertainPerformance Nov 05 '19 at 05:49
  • Seems like it is a function that is not assigned to anything but automatically executes itself - useless js – dan1st Nov 05 '19 at 05:49
  • Maybe it has educational purposes(scopes of `this` and `self`) – dan1st Nov 05 '19 at 05:51
  • Look up IIFE. It has its use cases, this does not seem like a valid one. – zero298 Nov 05 '19 at 05:51
  • _“If I remove the `;` after `let self = this;` then it does not work”_ — Why do you expect it to work? See [What are the rules for JavaScript's automatic semicolon insertion (ASI)?](https://stackoverflow.com/q/2846283/4642212). – Sebastian Simon Nov 05 '19 at 05:54
  • Well replace `self.name` in the `console.log` with some literal like `"hello"` and you will see the real error here: `'this' is not a function`. Semicolon is important in situations like this – Nuhman Nov 05 '19 at 06:00

1 Answers1

0

You don't have to use this and ;, and the code below makes it much simpler without using this, nor ;:

let obj = {
  name: 'john',
  getInfo: () => console.log(obj.name) 
}
obj.getInfo();
David
  • 15,894
  • 22
  • 55
  • 66