SoluableNonagon
SoluableNonagon

Reputation: 11755

AngularJS function hoisting

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/

Upvotes: 2

Views: 1629

Answers (1)

ilmatic
ilmatic

Reputation: 565

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.

Upvotes: 6

Related Questions