1

Here is mystic behavior of JavaScript. Does it my mistake of usage or some bug?

JavaScript code

function test(){

  var self = this;

  self.func1 = function(){
    debugger; // here self == Window
  }
  debugger; //here self == test func
  self.func1(); 
}

var t = new test();

I provided JSfiddle that you can try it by yourself:

https://jsfiddle.net/stanislavmachel/f44zbvvr/8/

Could somebody explain why context of self variable miss after call?

Stanislav Machel
  • 349
  • 2
  • 20

1 Answers1

2

It's not a bug, you're just reading the debugger wrong.

The JS engine notices that the function func1 doesn't use the variable self so as an optimization measure it doesn't include it in the context object. What you see in the debugger is the global self.

If you use the self variable inside the function, e.g. console.log(self), you'll also see it in the debugger's closure list. See https://jsfiddle.net/f44zbvvr/9/.

Community
  • 1
  • 1
JJJ
  • 32,902
  • 20
  • 89
  • 102