0

I ran into an issue with the naming of parameters and arguments. In the IIFE, when I pass this as an argument, why do I need to re-name it at the parameter side.

When I rename this, the function is able to refer to proper this. When I do not, I'm getting unexpected token this.

const obj = {
  foo: 'bar',
  met() {
    (function(global) {
      console.log(global); // works fine
    })(this);
  },
  met2() {
    (function(this) { // unexpected token this
      console.log(this);
    })(this);
  },
};

obj.met();
obj.met2();


I did not understand why I'm getting an unexpected token error.

Sai
  • 1
  • 2
    You can use `function() { console.log(this); }.call(this)` – Bergi Jul 21 '19 at 20:28
  • @Bergi I don't think I asked how to pass `this`. I asked why we should not name the parameter as `this` and Quentin has give the answer. – Sai Jul 21 '19 at 20:32
  • 1
    `this`, along with a list of other reserved words, cannot be use as variables, labels, or function names: See https://www.w3schools.com/js/js_reserved.asp, so for example, if you try to use `function(false) {...}` it will fail too. – Rico Chen Jul 21 '19 at 20:38
  • @SaiKrishnaSarathVelamuri I saw his answer, my comment is meant as a supplement to it. – Bergi Jul 21 '19 at 20:44
  • @Bergi I never knew duplicate and supplement meant the same. – Sai Jul 21 '19 at 20:51
  • @Sai My comment was not related to the duplicate vote. The duplicate has an answer that explains (amongst other things) why you were getting the *Uncaught SyntaxError: Unexpected token this*. – Bergi Jul 21 '19 at 20:57

1 Answers1

2

this is a keyword, so you can't create a new variable named this.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335