Development Tip

! function ($) {$ (function () {})} (window.jQuery)는 무엇을합니까?

yourdevel 2020. 11. 29. 12:23
반응형

! function ($) {$ (function () {})} (window.jQuery)는 무엇을합니까?


트위터 부트 스트랩을 사용하여 사이트를 만들고 툴팁을 초기화하려고했습니다. 다음과 같은 것을 추가하는 것 외에도 :

 $ ( "[rel = tooltip]"). tooltip ()  
application.js에서 부트 스트랩 문서에 사용 된 다음 코드를 유지하지 않는 한 내 툴팁이 초기화되지 않습니다.

! function ($) {

  $ (함수 () {  

  })

} (window.jQuery)

위의 코드는 무엇을합니까?


코드를 분할하여 설명하겠습니다.

function () {
}()

또는 종종 다음과 같이 작성됩니다.

(function () {
})()

IIFE (Immediately-Invoked Function Expressions)self-invoking anonymous 라고도 하는 함수 입니다. 익명 함수를 즉시 인라인으로 실행합니다.

이에 대한 자세한 내용 은 캡슐화 된 익명 함수 구문 설명을 참조하십시오 .

익명 함수는 강력한 기능이며 범위 지정 ( "변수 이름 간격")과 같은 이점 이 있습니다. 자바 스크립트에서 자체 실행 함수의 목적무엇입니까?를 참조하십시오 . .


이제 그들은 사용하고 있습니다

function ($) {

}(window.jQuery)

!지금 은 건너 뛰겠습니다 .

그래서 그들은 window.jQuery그 함수에 인자로 전달하고 $.

이것이하는 일은 (원본 jQuery 객체)에 $대한 별칭을 만들고 window.jQuery따라서 다른 라이브러리가 해당 ( )를 외부로 가져 갔는지 여부에 관계없이는 $항상 jQuery object내부를 참조하도록합니다 .closure$

따라서 해당 클로저 내부에 작성한 코드 $는 항상 작동합니다.

또 다른 이점은 $익명 함수의 인수로 제공되어 더 가까워 scope chain져서 JS 인터프리터가 $클로저 내부의 객체 를 찾는 데 걸리는 시간 이 global을 사용하는 경우보다 더 적게 걸린다는 $입니다.


$(function(){  

})

이미 알고있는 것처럼 jQuery의 문서 준비 블록으로,이 함수 내부의 코드가에서 실행 dom is ready되므로 모두 event binding's제대로 작동합니다.

http://api.jquery.com/ready/ 에서 자세히 알아보세요.

그리고 여기! 에 잘 설명되어 있습니다. 또는 기능 전에 느낌표무엇을합니까?

간단히 말해서 :

의 이점을 설명하기 !위해 사례를 살펴 보겠습니다.

(function() {
    alert('first');
}())


(function() {
    alert('second');
}())

위의 코드를에 붙여 넣으면 console두 개의 경고가 표시되지만이 오류가 발생합니다.

TypeError: undefined is not a function

왜 이런 일이 발생합니까? JS 엔진이 위 코드 블록을 실행하는 방법을 시뮬레이션 해 보겠습니다. 이 익명 함수를 실행 function() {alert('first');}()하여 경고를 표시 undefined하고 (). 두 번째 기능도 마찬가지입니다. 따라서이 블록을 실행 한 후에는 다음과 같은 결과를 얻게됩니다.

(undefined)(undefined)

구문이 self-invoking anonymous함수 와 같기 때문에 해당 함수를 호출하려고하지만 첫 번째 (undefined)는 함수가 아닙니다. 따라서 undefined is not a function오류가 발생합니다. !이러한 종류 또는 오류를 수정합니다. 무엇으로 발생 !. 위의 답변 링크의 줄을 인용하고 있습니다.

!를 사용하면 함수는 단항 (논리) NOT 연산자의 단일 피연산자가됩니다.

This forces the function to be evaluated as an expression, which allows it to be invoked immediately inline.

and this solves the above problem, we can rewrite the above block using ! like

!(function() {
    alert('first');
}())


!(function() {
    alert('second');
}())

For your case you can simply put your tooltip code inside a document ready block like this

$(function(){  
    $("[rel=tooltip]").tooltip();  
});

and it will work fine.

And if you just use $("[rel=tooltip]").tooltip() without any doc ready block, then there is a chance when this code will run, there isn't any element with rel=tooltip in DOM yet. So $("[rel=tooltip]") will return an empty set and tooltip won't work.

An example markup when it won't work without doc ready block,

.
.
.
<script type="text/javascript">
    $("[rel=tooltip]").tooltip();
</script>
.
.
.
.
<a href="#" rel="tooltip">Something</a>
<a href="#" rel="tooltip">Something</a>
<a href="#" rel="tooltip">Something</a>

As browsers, interprets the markup sequentially, it will execute the js code as soon as it face it as. And when it executes the JS block here, it hasn't yet parsed the a rel="tooltip" tags yet, as it appears after the JS block, So they are not in DOM at that moment.

So for the above case $("[rel=tooltip]") is empty and hence tooltip won't work. So it's always safe to put all your JS code inside document ready block like

$(function){
    // put all your JS code here
});

Hope all this makes sense to you now.

참고URL : https://stackoverflow.com/questions/10896749/what-does-function-function-window-jquery-do

반응형