2016-09-02 3 views
3

나는 각도 꽤 새로운 해요,하지만 다음과 같이 내 응용 프로그램에서 디버깅 최근의 문제는 갔다 : 각도 모듈 기능 : var?

내가 다른의 .js 파일에 정의 된 기존 모듈에 새로운 지시를 부착하고있어 말. 나는 다음과 같은 구문을 사용하는 경우 :

angular 
.module('myApp') 
.directive('ratingStars', ratingStars) 
; 

var ratingStars = function(){ 
    return { 
    restrict: 'EA', 
    scope: {thisRating : '=rating'}, 
    templateUrl: '/my.template.html' 
    }; 
}; 

를 내가의 라인을 따라, 오류가 발생하는 것 "인수 'FN 것은'정의되지있어 기능하지 않습니다."

그러나 다음과 같이 코드를 수정할 수 있습니다 (var에 할당하는 대신 직접 함수를 사용하십시오).

angular 
.module('myApp') 
.directive('ratingStars', ratingStars) 
; 

function ratingStars(){ 
    return { 
    restrict: 'EA', 
    scope: {thisRating : '=rating'}, 
    templateUrl: '/my.template.html' 
    }; 
} 

제 기능을 복용하고 할당 var에에보다는 크게 함수를 정의의 논리적 차이점은 무엇입니까? 일종의 가변 호이 스팅이 진행되고 있습니까? 내 var은 그 하나의 파일에 대해서만 로컬입니까?

감사합니다.

답변

5

관련 항목 top hoisting.

기능을 완전히 정의하지 않고 var에 할당하는 것의 논리적 인 차이점은 무엇입니까? 첫 번째 스크립트에서

, 귀하의 스크립트로 해석됩니다

은 다음과 같습니다.

var ratingStars; 

angular 
    .module('myApp') 
    .directive('ratingStars', ratingStars); 

ratingStars = function() { 
    return { 
     restrict: 'EA', 
     scope: { thisRating: '=rating' }, 
     templateUrl: '/my.template.html' 
    }; 
}; 

그래서, 당신은 자바 스크립트의 변수가 var가 정상 기능 범위 block scope 또는 전역 범위에 게양되어 사용하여 선언 때문에 var ratingStarsdeclared first and assigned it to the directive definition .Its입니다 볼 수 있습니다. But actual definition will occur after that. 두 번째 스크립트에서

, 귀하의 function definition

가 글로벌 코드의 상단에 정의됩니다. 그래서 올바르게 해석됩니다. function defination itself getting top hoisted

+0

그것이 down-voted.?Please이 댓글을 추가 왜 여기서 variable getting top hoisted

하지만 not actual function definition와 두 번째는 function defination

를 사용하는 경우

그래서, 첫 번째는 function expression 사용 –