0

Consider the snippet in Javascript,

        var objt = {

            fn :    function(three, four){
                    four();             //    window as (this === window)
                }
        }       


        objt.fn(3, function(){
            alert(this);         //    window as (this === window)

        });

The above is not a constructor function. Inside a function, the value of this depends on how the function is called. The function

            function(){
                alert(this);                    
            }

was passed as an argument and as such wasn't linked to the objt. No issues with this.

Now consider the snippet in AngularJS regarding module and controller,

myModule.controller('MainCtrl', function(x1, x2) {
    var main = this;

    alert(this === window);  // alert false, why and what is this here?

});
Farhan stands with Palestine
  • 13,890
  • 13
  • 58
  • 105
  • It could be the controller itself or the $scope http://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers – michelem Aug 24 '15 at 08:18
  • Check this http://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers?rq=1 – Chandermani Aug 24 '15 at 08:18

1 Answers1

2

Generally this is a tricky one and internally depends on the scope you are in. If you declare function in global scope, this will be equal to the window since window is the global scope.

However since you are inside controller scope in Angular, this no longer refers to the window object, thus it becomes your controller object.

kamil-mrzyglod
  • 4,948
  • 1
  • 20
  • 29