sourcetip

익명 함수로 컨트롤러 래핑

fileupload 2023. 3. 29. 21:45
반응형

익명 함수로 컨트롤러 래핑

할지 안 할지:

(function () {
'use strict';

// Create the module and define its dependencies.
var app = angular.module('app', [
    // Angular modules 
    'ngAnimate',        // animations
    'ngRoute'           // routing

    // Custom modules 

    // 3rd Party Modules

]);

// Execute bootstrapping code and any dependencies.
app.run(['$log',
    function ($log) {
        $log.log('we are loaded');
    }]);
})();

또는

'use strict';

// Create the module and define its dependencies.
var app = angular.module('app', [
    // Angular modules 
    'ngAnimate',        // animations
    'ngRoute'           // routing

    // Custom modules 

    // 3rd Party Modules

]);

// Execute bootstrapping code and any dependencies.
app.run(['$log',
    function ($log) {
        $log.log('we are loaded');
    }]);

둘 다 효과가 있는 것 같습니다.차이가 뭐죠?

AngularJs에 대해 익명의 함수가 무엇인지, 언제 사용하는지, 컨트롤러가 쌍방향으로 표시되는 이유를 설명해 주시면 감사하겠습니다.

감사합니다!

둘 다 잘 될 거예요.어나니머스 함수에 싸인 자바스크립트 코드를 많이 찾을 수 있는 이유는 페이지의 다른 코드와 분리하기 위해서입니다.

다음 코드는 다음 변수를 선언합니다.name글로벌 범위:

var name = "Hello World";

이 코드를 사용함으로써 페이지 상의 다른 모든 스크립트가 다음과 같은 변수를 사용하려고 합니다.name잠재적으로 예기치 않은 값을 얻을 수 있다"Hello World"왜냐면 네 대본이 그걸 선언했으니까"Hello World".

이 코드를 어나니머스 함수로 래핑함으로써 코드가 다른 변수와 충돌하지 않도록 할 수 있습니다.name:

(function() {
    var name = "Hello World";
})();

위의 예에서는name이제 익명 기능의 범위 내에서만 사용할 수 있습니다.글로벌하지 않기 때문에 페이지의 다른 코드와 경합할 수 없습니다.

당신이 제공한 두 번째 코드 조각에서,app글로벌 변수를 선언하는 다른 사용자가 덮어쓸 수 있는 글로벌 변수가 될 수 있습니다.appAngular 모듈을 익명 함수로 감싸는 것으로, 코드가 다른 코드와 경합하는 것을 방지할 수 있습니다.

또한 코드를 사용할 수 있는 다른 사용자는 코드를 사용하여 글로벌 범위를 변경할 필요가 없습니다.

JavaScript의 로컬 변수는 함수 범위에만 존재합니다!

따라서 IIFE(Imediate-Incurrated Function Expression)를 사용하는 경우는 다음과 같습니다.

(function () {
   var app = angular.module('app', []);
})();

다음 기능 이외에는 모듈에 액세스할 수 없습니다.

(function () {
   var app = angular.module('app', []);
})();

// will get app is undefined error
app.run(['$log', function ($log) {
    $log.log('we are loaded');
}]);

전역 변수 대신 로컬 변수를 선언하는 것이 좋습니다.그러면 글로벌 환경에서 앱 변수에 액세스할 수 없습니다.

글로벌 변수를 선언하면 변수는 어디서나 사용할 수 있으며 다른 Javascript 프로그램과 충돌할 수 있습니다.

언급URL : https://stackoverflow.com/questions/21445817/wrapping-controller-in-anonymous-function

반응형