'$ (this)'와 'this'의 차이점은 무엇입니까?
저는 현재이 튜토리얼을 진행하고 있습니다 : jQuery 시작하기
아래 두 가지 예 :
$("#orderedlist").find("li").each(function (i) {
$(this).append(" BAM! " + i);
});
$("#reset").click(function () {
$("form").each(function () {
this.reset();
});
});
첫 번째 예에서 $(this)
각 li
요소 내부에 텍스트를 추가 하는 데 사용 합니다 . 두 번째 예 this
에서는 양식을 재설정 할 때 직접 사용 합니다.
$(this)
보다 더 자주 사용되는 것 같습니다 this
.
내 추측은 첫 번째 예제에서 $()
각 li
요소를 append()
함수 를 이해하는 jQuery 객체로 변환 하는 반면 두 번째 예제 reset()
에서는 양식에서 직접 호출 할 수 있습니다.
기본적으로 $()
특별한 jQuery 전용 함수 가 필요 합니다.
이 올바른지?
예, $()
jQuery를 사용할 때만 필요합니다 . DOM 작업을 수행하는 데 jQuery의 도움을 받으려면 이것을 명심하십시오.
$(this)[0] === this
기본적으로 요소 집합을 다시 가져올 때마다 jQuery는이를 jQuery 객체 로 변환 합니다 . 결과가 하나만 있다는 것을 안다면 첫 번째 요소에있을 것입니다.
$("#myDiv")[0] === document.getElementById("myDiv");
등등...
$()
jQuery 생성자 함수입니다.
this
호출의 DOM 요소에 대한 참조입니다.
그러니까 기본적으로,에 $(this)
, 당신은 단지를 통과하는 this
에 $()
당신이 jQuery를 방법과 함수를 호출 할 수 있도록 매개 변수로.
예, $(this)
jQuery 함수 가 필요 하지만 jQuery를 사용하지 않는 요소의 기본 자바 스크립트 메소드에 액세스하려면 this
.
사용하는 경우 jQuery
, 사용하는 것이 좋습니다 $(this)
보통. 그러나 차이점을 알고 있다면 (배우고 알고 있어야 함) .NET Framework를 사용하는 것이 더 편리하고 빠를 때도 있습니다 this
. 예를 들면 :
$(".myCheckboxes").change(function(){
if(this.checked)
alert("checked");
});
보다 쉽고 순수합니다
$(".myCheckboxes").change(function(){
if($(this).is(":checked"))
alert("checked");
});
this
요소이고 $(this)
해당 요소로 구성된 jQuery 객체입니다.
$(".class").each(function(){
//the iterations current html element
//the classic JavaScript API is exposed here (such as .innerHTML and .appendChild)
var HTMLElement = this;
//the current HTML element is passed to the jQuery constructor
//the jQuery API is exposed here (such as .html() and .append())
var jQueryObject = $(this);
});
더 깊은 모습
this
MDN 은 실행 컨텍스트에 포함됩니다.
범위는 현재 실행 컨텍스트 ECMA를 나타냅니다 . 이해하기 위해서 this
, 실행 컨텍스트는 자바 스크립트에서 작동하는 방식을 이해하는 것이 중요합니다.
실행 컨텍스트는 이것을 바인딩합니다.
When control enters an execution context (code is being executed in that scope) the environment for variables are setup (Lexical and Variable Environments - essentially this sets up an area for variables to enter which were already accessible, and an area for local variables to be stored), and the binding of this
occurs.
jQuery binds this
Execution contexts form a logical stack. The result is that contexts deeper in the stack have access to previous variables, but their bindings may have been altered. Every time jQuery calls a callback function, it alters the this binding by using apply
MDN.
callback.apply( obj[ i ] )//where obj[i] is the current element
The result of calling apply
is that inside of jQuery callback functions, this
refers to the current element being used by the callback function.
For example, in .each
, the callback function commonly used allows for .each(function(index,element){/*scope*/})
. In that scope, this == element
is true.
jQuery callbacks use the apply function to bind the function being called with the current element. This element comes from the jQuery object's element array. Each jQuery object constructed contains an array of elements which match the selectorjQuery API that was used to instantiate the jQuery object.
$(selector)
calls the jQuery function (remember that $
is a reference to jQuery
, code: window.jQuery = window.$ = jQuery;
). Internally, the jQuery function instantiates a function object. So while it may not be immediately obvious, using $()
internally uses new jQuery()
. Part of the construction of this jQuery object is to find all matches of the selector. The constructor will also accept html strings and elements. When you pass this
to the jQuery constructor, you are passing the current element for a jQuery object to be constructed with. The jQuery object then contains an array-like structure of the DOM elements matching the selector (or just the single element in the case of this
).
Once the jQuery object is constructed, the jQuery API is now exposed. When a jQuery api function is called, it will internally iterate over this array-like structure. For each item in the array, it calls the callback function for the api, binding the callback's this
to the current element. This call can be seen in the code snippet above where obj
is the array-like structure, and i
is the iterator used for the position in the array of the current element.
Yeah, by using $(this)
, you enabled jQuery functionality for the object. By just using this
, it only has generic Javascript functionality.
this
reference a javascript object and $(this)
used to encapsulate with jQuery.
Example =>
// Getting Name and modify css property of dom object through jQuery
var name = $(this).attr('name');
$(this).css('background-color','white')
// Getting form object and its data and work on..
this = document.getElementsByName("new_photo")[0]
formData = new FormData(this)
// Calling blur method on find input field with help of both as below
$(this).find('input[type=text]')[0].blur()
//Above is equivalent to
this = $(this).find('input[type=text]')[0]
this.blur()
//Find value of a text field with id "index-number"
this = document.getElementById("index-number");
this.value
or
this = $('#index-number');
$(this).val(); // Equivalent to $('#index-number').val()
$(this).css('color','#000000')
참고URL : https://stackoverflow.com/questions/1051782/whats-the-difference-between-this-and-this
'Nice programing' 카테고리의 다른 글
레이크 스펙을 실행하지 않고 Rails rspec 테스트를 위해 테스트 데이터베이스를 준비하려면 어떻게해야합니까? (0) | 2020.10.04 |
---|---|
Android 네트워킹 라이브러리 비교 : OkHTTP, Retrofit 및 Volley (0) | 2020.10.03 |
Swift에서 dispatch_once 싱글 톤 모델 사용 (0) | 2020.10.03 |
Twitter Bootstrap을 사용하여 중앙 집중식 콘텐츠를 얻으려면 어떻게해야합니까? (0) | 2020.10.03 |
Bash에서 문자열을 배열로 분할 (0) | 2020.10.03 |