programing

jQuery에서 "this"는 무엇을 의미합니까?

projobs 2021. 1. 14. 08:02
반응형

jQuery에서 "this"는 무엇을 의미합니까?


이 질문에 이미 답변이 있습니다.

jquery에서 this의미 는 무엇 이며 언제 사용됩니까?


thisJavaScript에서 매우 특별하고 강력합니다. 그것은 거의 모든 것을 의미 할 수 있습니다. 여기여기 에서 일부를 다루지 만 JavaScript에 대한 좋은 자습서를 찾아서 시간을 보내는 것은 정말 가치가 있습니다.

먼저 jQuery의 사용법을 살펴본 다음 JavaScript로 좀 더 일반적으로 이야기 해 봅시다.

특히 jQuery에서

jQuery로 작성된 코드에서 this 일반적 으로 호출되는 함수의 주제 인 DOM 요소를 참조합니다 (예 : 이벤트 콜백에서).

예 jQuery를 이벤트 콜백 (무엇 this에 덮여있다 문서 ) :.bind

$("div").click(function() {
    // Here, `this` will be the DOM element for the div that was clicked,
    // so you could (for instance) set its foreground color:
    this.style.color = "red";

    // You'll frequently see $(this) used to wrap a jQuery object around the
    // element, because jQuery makes lots of things a lot simpler. You might
    // hide the element, for example:
    $(this).hide();
});

마찬가지로 현재 jQuery 선택기와 일치하는 모든 요소에 대해 작동하는 다양한 jQuery 함수는 선택적으로 함수를 허용 할 수 있으며 해당 함수가 호출되면 this다시 해당 DOM 요소가됩니다. 예를 들어이 html함수는 다음을 허용합니다.

// Find all divs inside the `foo` element, and set
// their content to their CSS class name(s)
// (Okay, so it's a hokey example)
$("#foo div").html(function() {
    return this.className;
});

jQuery가 사용하는 또 다른 장소 this는 콜백에 있습니다 jQuery.each.

var a = ["one", "two", "three"];
jQuery.each(a, function() {
    alert(this);
});

... "1", "2", "3"순으로 경고합니다. 보시다시피 이것은 완전히 다른 this.

(혼동 JQuery와이라는 두 가지 기능을 갖는다 eachJQuery와에있는 하나의 위 / $ 함수 자체 항상 호출을 그런 식으로 [ jQuery.each(...)또는 $.each(...),과의 jQuery의 다른 하나의 경우 [개체]보다는 JQuery와 / $ 함수 iself. 여기 다른 하나에 대한 문서 이며, this동일한 방식 html과 이벤트 콜백을 사용하기 때문에이 답변에서 다른 하나를 논의하지 않으며 jQuery 에서 다른 용도 를 보여주고 싶었습니다 this.)

일반적으로 JavaScript에서

this객체를 나타냅니다. 업데이트 : ES5의 엄격 모드에서는 더 이상 사실이 아니며 this어떤 값도 가질 수 있습니다. this주어진 함수 호출 내의 값은 함수가 호출되는 방식에 따라 결정됩니다 (C # 또는 Java와 같은 언어에서와 같이 함수가 정의 된 위치가 아님). this함수를 호출 설정하는 가장 일반적인 방법 은 객체의 속성을 통해 함수를 호출하는 것입니다.

var obj = {};
obj.foo = function() {
    alert(this.firstName);
};
obj.firstName = "Fred";
obj.foo(); // alerts "Fred"

우리가 호출 때문에이은 foo에 속성을 통해 obj, this로 설정 obj호출의 기간 동안. 그러나 foo어떤 식 으로든와 결혼 한 인상을받지 마십시오 obj. 이것은 잘 작동합니다.

var obj = {};
obj.foo = function() {
    alert(this.firstName);
};
obj.firstName = "Fred";
obj.foo(); // alerts "Fred"

var differentObj = {};
differentObj.firstName = "Barney";
differentObj.bar = obj.foo; // Not *calling* it, just getting a reference to it
differentObj.bar(); // alerts "Barney"

실제로 어떤 객체 에도foo 본질적으로 연결되어 있지 않습니다 .

var f = obj.foo; // Not *calling* it, just getting a reference to it
f(); // Probably alerts "undefined"

f객체 속성을 통해 호출하지 않았기 때문에 this명시 적으로 설정되지 않았습니다. this명시 적으로 전역 객체가 기본값이 설정되어 있지 않은 (어떤 window브라우저에서). window속성이 없을 수 firstName있으므로 경고에 "정의되지 않음"이 표시됩니다.

어떤 기능 세트를 호출하는 다른 방법이 있습니다 this함수의 사용하여 :입니다 .call.apply기능 :

function foo(arg1, arg2) {
    alert(this.firstName);
    alert(arg1);
    alert(arg2);
}

var obj = {firstName: "Wilma"};
foo.call(obj, 42, 27); // alerts "Wilma", "42", and "27"

callthis지정한 첫 번째 인수로 설정 한 다음 다른 인수와 함께 호출하는 함수에 전달합니다.

apply 정확히 똑같은 일을하지만 함수에 대한 인수를 개별적으로가 아닌 배열로 제공합니다.

var obj = {firstName: "Wilma"};
var a   = [42, 27];
foo.apply(obj, a); // alerts "Wilma", "42", and "27"
//             ^-- Note this is one argument, an array of arguments for `foo`

다시 말하지만, thisJavaScript에서 더 많은 것을 탐구 할 수 있습니다. 이 개념은 강력하고, 다른 언어에 익숙한 경우가 아니라 다른 언어가 사용하는 방식에 익숙하고 알 가치가있는 경우 약간 기만적입니다.

다음은 thisES5의 엄격 모드에서 객체를 참조하지 않는 몇 가지 예입니다 .

(function() {
    "use strict";   // Strict mode

    test("direct");
    test.call(5, "with 5");
    test.call(true, "with true");
    test.call("hi", "with 'hi'");

    function test(msg) {
        console.log("[Strict] " + msg + "; typeof this = " + typeof this);
    }
})();

산출:

[엄격] 직접; typeof this = 정의되지 않음
[엄격] 5 개; 이 유형 = 숫자
[엄격한] 사실로; typeof this = 부울
[엄격] '안녕'으로; typeof this = 문자열

느슨한 모드에서는 모두 다음과 같이 말했을 것입니다 typeof this = object. 라이브 카피 .


this 키워드

JavaScript에서 이것을 호출하는 것은 JavaScript 코드를 "소유"하는 객체입니다.

The value of this, when used in a function, is the object that "owns" the function.The value of this, when used in an object, is the object itself. The this keyword in an object constructor does not have a value. It is only a substitute for the new object.The value of this will become the new object when the constructor is used to create an object.

Note that this is not a variable. It is a keyword. You cannot change the value of this.


Here is how i would explain it, simply:

this refers to the object that called the function.

so looking at this:

var foo = {
  name: "foo",
  log: function(){
    console.log(this.name);
  }
}

var bar = {
  name: "bar"
}
bar.log = foo.log;
bar.log();

the bar object stores a reference of foo's log method into it's own log property for itself. now when bar calls its log method, this will point to bar because the method was called upon by the bar object.

this works for any other object, even the window object. if you call a function via the global scope, this will point to the window object.

by using the bind or call methods of a function, you can explicitly define what the object this will refer to during execution.

Fun fact: anything defined in the global scope, which is the top layer/level, becomes a property of the window object (global scope = window object).


Top Google result for "javascript this": http://www.quirksmode.org/js/this.html

Edit: I think the key sentence is:

"In JavaScript "this" always refers to the “owner” of the function we're executing, or rather, to the object that the function is a method of."

Quirksmode is (generally*) excellent, worth reading the whole article in detail.

*Apparently this statement is not necessarily correct, see T.J. Crowder's comment below.


The keyword this acts as a placeholder, and will refer to whichever object called that method when the method is actually used in Java Script


The same object that invokes the function is passed to the function as this parameter.

When an object is created from a class it contains only a set of properties and there is no function in the object. And the functions belong to the class. however, how is a function called by an object?

Consider the following code.

var obj = {
            p1: 'property 1',

            func1 () {
                return this.p1
            },

            func2 (param) {
                return this.p1 + param
            }
    }

And also call functions by obj object

obj.func1 ();
obj.func2 ('A');

The compiler adds the this parameter to the beginning of the function parameters. And actually compiled functions are as follows.

var obj = {
            p1: 'property 1',

            func1 (this) {
                return this.p1
            },

            func2 (this, param) {
                return this.p1 + param
            }
    }

And the compiled function call also changes as follows.

func1 (obj);
func2 (obj, 'A');

ReferenceURL : https://stackoverflow.com/questions/4195970/what-does-this-mean-in-jquery

반응형