1

Forgive me if this is a basic question but I come from a desktop c# background and this javascript nested functions pattern seems a bit odd to grasp. This isn't strictly related to angular, more of a javascript question. It seems that on tons of sites/tutorials nested functions are heavily used,

HTML

<div ng-controller="MyController">
  <button ng-click="sayHello()">Hello</button>
</div>

For this contrived example, when this button is clicked, it will show a hello world message

function MyController($scope) {
    $scope.sayHello =function sayhello(){
    alert("hello world");
};

However , we could just as easily separate the inner function to make the script easier to read, like so

var sayHelloVariable = function sayhello() {
    alert("hello world");
};

function MyController($scope) {
    $scope.sayHello = sayHelloVariable;
};

For this simple example we only have a few lines but I have seen tutorials with lines upon lines of nested functions making it hard to understand what is going on ( or perhaps I will come around to javascript way of thinking in time?)

Is there a particular reason why nesting functions is so popular, perhaps a performance reason?

Thanks

5
  • 2
    In your second example, sayHelloVariable is now polluting the parent scope. Commented Jun 24, 2014 at 7:58
  • 1
    C# has lambda expressions, which could be used to write that simple functions too, and I wuld use them for situations like this (In your example, if I write something like that in C#, I will use a lambda too). So the situation is the same as in C# Commented Jun 24, 2014 at 8:00
  • I think this has to do with scope of variables, Also JS heads like to miniminimize everything we possibly can ;) Commented Jun 24, 2014 at 8:00
  • When learning a new language I strongly suggest conforming to the practices of that language. There's usually a good reason for them. Javascript does not have block scope, so as @NiettheDarkAbsol pointed out your example is leaking the variable. Commented Jun 24, 2014 at 8:03
  • 1
    If you haven't done already, I strongly suggest reading up on closures. This will probably shed a different light on why one uses nested functions. Commented Jun 24, 2014 at 8:08

1 Answer 1

1

With angular, unless you need to reuse that function, any functions relating to that controller are best defined inside that controller, as in the first example. It's better not to pollute the parent scope with tons of random functions. Think of the function MyConroller($scope) more as a class definition than as a function definition.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.