2

I have created a plunkr, as you can see I have called the functions once from $scope.init which works as expected where as when I create a separate

function exec(){
  this.data = "234"
    function es5(){
      console.log(this.data) //<-- Has access ?
    }
    es5();
    es6 = () => {
      console.log(this.data)
    }
    es6();
}

and called it from $scope.init, the function has access to this

Take a look at console of browser once the plunker is loaded

deceze
  • 471,072
  • 76
  • 664
  • 811
User985614
  • 192
  • 1
  • 13
  • 1
    Because you didn't implicitly bind function `es5`, it is default binded and gets parent scope as `this` value. – Anurag Awasthi Apr 03 '18 at 06:53
  • @nrgwsth : ok, but how is it is not getting binded in case of `init` function ? – User985614 Apr 03 '18 at 06:56
  • `this` inside `es5` is `window`. If `window.data` is anything useful, that's because you have set something to `window.data` before, probably using the same technique. E.g., if you execute `exec` as just `exec()`, `this` inside `exec` is `window` as well. – deceze Apr 03 '18 at 07:12
  • Please show us how `exec` is called. If you just do `exec()` like you did `es5()`, their `this` is indeed the same thing. Also, always use strict mode! – Bergi Apr 03 '18 at 09:39

0 Answers0