1

I tried below code to understand IIFE behaviour inside class methods. Intrestingly I get undefined when I try to print the variable inside IIFE.

window.numValue=0;

class ArOps {
 constructor (){
   this.numValue = 0;
 }
 add(){
   this.numValue += 10;
   console.log(this.numValue);
   (function(){
     console.log(this.numValue);
   })();
 }
}

let arOps = new ArOps();

arOps.add();

Even though window object contains the 'numValue' variable, console.log throws error

window.numValue=0;

class ArOps {
 constructor (){
   this.numValue = 0;
 }
 add(){
   this.numValue += 10;
   console.log(this.numValue);
   (function(){
     console.log(this.numValue);
   }).call(window);
 }
}

let arOps = new ArOps();

arOps.add();

But the same code refers to 'numValue' variable in window object when I assign 'window' inside call method.

Can anyone help me understand the reason for initial error?

Sharan
  • 11
  • 2
  • 3
    Welcome to SO. Please post your code as text not as images. See: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) – charlietfl Feb 27 '21 at 20:15
  • Your problem is `this` has a different context inside `function`. – charlietfl Feb 27 '21 at 20:17
  • 1
    @charlietfl, Thank you for your suggestion. I have updated the question. Could you please explain bit more w.r.t 'this' having different context? Like where would the IIFE function refer to in the above example – Sharan Feb 27 '21 at 20:20
  • Try using ES6 arrow function for the IIFE ... `(()=> { console.log(this.numValue)})()`; An arrow function has no expicit `this` the way a standard `function` does – charlietfl Feb 27 '21 at 20:22
  • That's a not a great dupe target from @charlietfl. There *is* probably another answer that's a better fit. The primary issue is that es6 classes are executed in `strict` mode. As a result `this` does not default to the window object. – Mark Feb 27 '21 at 20:26

0 Answers0