简体   繁体   中英

Is it necessary to use nested functions in javascript?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM