2

I have a 'beginner' question. Why does this error out? I call the function in the code, but the function is defined further down.

AngularJS version:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.name = 'Someone';
    $scope.doStuff(); // run the defined function, but errors out

    $scope.doStuff= function(){  // function definition
        console.log('did something');
    }
}

http://jsfiddle.net/2fjuJ/4/

But this one works fine:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.name = 'Someone';
    $scope.doStuff = function(){
        console.log('did something');
    }

    $scope.doStuff(); 
}

http://jsfiddle.net/2fjuJ/5/

SoluableNonagon
  • 11,541
  • 11
  • 53
  • 98

1 Answers1

6

You're not declaring a new variable when you write $scope.doStuff = function () {...}, you're assigning a property, which does not get hoisted. at the time you call $scope.doStuff(), $scope looks like:

{
    name: "Someone"
}

As you can see there's no "doStuff" property until the next line executes.

ilmatic
  • 565
  • 3
  • 11