“this"是什么意思?在 jQuery 中是什么意思? [英] What does "this" mean in jQuery?

查看:105
本文介绍了“this"是什么意思?在 jQuery 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jquery中,this是什么意思,什么时候用?

解决方案

this 在 JavaScript 中非常特殊和强大.它可以意味着任何事情.我在这里这里,但是找到一个关于 JavaScript 的好教程并花一些时间来学习它真的很值得.

我们先看看jQuery的使用,然后在JavaScript中更一般地谈论它(有点).

在 jQuery 中,特别是

在用 jQuery 编写的代码中,this通常指的是作为被调用函数主题的 DOM 元素(例如,在事件回调中).>

示例 jQuery 事件回调(this 包含在 中.绑定文档):

$("div").click(function() {//这里,`this` 将是被点击的 div 的 DOM 元素,//所以你可以(例如)设置它的前景色:this.style.color = "红色";//您会经常看到 $(this) 用于将 jQuery 对象包裹在//元素,因为 jQuery 使很多事情变得更简单.你可能//隐藏元素,例如:$(this).hide();});

类似地,作用于当前 jQuery 选择器匹配的所有元素的各种 jQuery 函数可以选择接受一个函数,当该函数被调用时,this 又是有问题的 DOM 元素.—例如,html 函数允许这样做:

//查找`foo`元素内的所有div,并设置//他们的内容到他们的 CSS 类名//(好吧,这是一个假的例子)$("#foo div").html(function() {返回 this.className;});

jQuery 使用 this 的另一个地方是在 jQuery 的回调中.each:

var a = ["一", "二", "三"];jQuery.each(a, function() {警报(这个);});

...这将提醒一",然后是二",然后是三".如您所见,这是 this 的完全不同用法.

(令人困惑的是,jQuery 有两个名为 each 的函数,上面的一个在 jQuery/$ 函数本身上,并且总是以这种方式调用 [jQuery.each(...)$.each(...)],以及 jQuery instances [objects] 上的一个不同的代码,而不是 jQuery/$ 函数本身.这是另一个的文档,我不在这个答案中讨论另一个,因为它使用 thishtml 和事件回调的方式相同,我想展示 不同 jQuery 对 this 的使用.)

一般在 JavaScript 中

this 引用一个对象. 更新: 从 ES5 的严格模式开始,这不再是真的,this 可以有任何值.this 在任何给定函数调用中的值取决于函数的调用方式(而不是定义函数的位置,如在 C# 或 Java 等语言中).在调用函数时设置 this 的最常见方法是通过对象上的属性调用函数:

var obj = {};obj.foo = 函数(){警报(this.firstName);};obj.firstName = "弗雷德";obj.foo();//提醒弗雷德"

那里,因为我们通过 obj 上的属性调用了 foothis 被设置为 obj通话时长.但是不要觉得 foo 以任何方式与 obj 结合,这很好用:

var obj = {};obj.foo = 函数(){警报(this.firstName);};obj.firstName = "弗雷德";obj.foo();//提醒弗雷德"var differentObj = {};differentObj.firstName = "巴尼";differentObj.bar = obj.foo;//不是*调用*它,只是获取对它的引用differentObj.bar();//提醒巴尼"

事实上,foo 根本不与任何 对象绑定:

var f = obj.foo;//不是*调用*它,只是获取对它的引用F();//可能提示未定义"

那里,因为我们没有通过对象属性调用 fthis 没有明确设置.当 this 未明确设置时,它默认为全局对象(在浏览器中为 window).window 可能没有属性 firstName,所以我们在我们的警报中得到了undefined".

还有其他方法可以调用函数并设置this是什么:通过使用函数的.call.apply函数:

function foo(arg1, arg2) {警报(this.firstName);警报(arg1);警报(arg2);}var obj = {firstName: "Wilma"};foo.call(obj, 42, 27);//提醒Wilma"、42"和27"

callthis 设置为您给它的第一个参数,然后将您给它的任何其他参数传递给它正在调用的函数.

apply 做完全一样的事情,但是你把函数的参数作为一个数组而不是单独给它:

var obj = {firstName: "Wilma"};var a = [42, 27];foo.apply(obj, a);//提醒Wilma"、42"和27"//^-- 注意这是一个参数,`foo` 的参数数组

不过,关于 JavaScript 中的 this 还有很多东西需要探索.这个概念很强大,如果你习惯了其他一些语言的做法(而不是如果你习惯了其他语言),那么这个概念有点欺骗性,值得了解.

以下是一些 this 在 ES5 的严格模式下不引用对象的示例:

(function() {严格使用";//严格模式测试(直接");test.call(5, "with 5");test.call(true, "with true");test.call("hi", "with 'hi'");功能测试(味精){console.log("[Strict] " + msg + "; typeof this = " + typeof this);}})();

输出:

[严格] 直接;typeof this = 未定义【严格】同5;typeof this = 数字【严格】同真;typeof this = 布尔值【严】同'嗨';typeof this = string

而在松散模式下,所有这些都会说 typeof this = object;实时复制.

In jquery, what does this means and when it is used?

解决方案

this in JavaScript is very special and powerful. It can mean just about anything. I cover some of it here and here, but it's really worth finding a good tutorial on JavaScript and spending some time with it.

Let's look at jQuery's use of it first, then talk about it more generally in JavaScript (a bit).

In jQuery, specifically

In code written with jQuery, this usually refers to the DOM element that's the subject of the function being called (for instance, in an event callback).

Example jQuery event callback (what this is is covered in the .bind docs):

$("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();
});

Similarly, various jQuery functions that act on all of the elements matched by the current jQuery selector can optionally accept a function, and when that function gets called, this is again the DOM element in question — for instance, the html function allows this:

// 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;
});

Another place jQuery uses this is in the callback on jQuery.each:

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

...which will alert "one", then "two", then "three". As you can see, this is a totally different usage of this.

(Confusingly, jQuery has two functions called each, the one above which is on the jQuery/$ function itself and always called that way [jQuery.each(...) or $.each(...)], and a different one on jQuery instances [objects] rather than the jQuery/$ function iself. Here are the docs for the other one, I don't discuss the other one in this answer because it uses this the same way html and event callback do, and I wanted to show a different use of this by jQuery.)

Generically in JavaScript

this refers to an object. Update: As of ES5's strict mode, that's no longer true, this can have any value. The value of this within any given function call is determined by how the function is called (not where the function is defined, as in languages like C# or Java). The most common way to set up this when calling a function is by calling the function via a property on the object:

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

There, because we called foo via a property on obj, this was set to obj for the duration of the call. But don't get the impression that foo is in any way married to obj, this works just fine:

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"

In fact, foo isn't intrinsically tied to any object at all:

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

There, since we didn't call f via an object property, this wasn't explicitly set. When this isn't explicitly set, it defaults to the global object (which is window in browsers). window probably doesn't have a property firstName, and so we got "undefined" in our alert.

There are other ways to call functions and set what this is: By using the function's .call and .apply functions:

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"

call sets this to the first argument you give it, and then passes along any other arguments you give it to the function it's calling.

apply does exactly the same thing, but you give it the arguments for the function as an array instead of individually:

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`

Again, though, there's a lot more to explore about this in JavaScript. The concept is powerful, a bit deceptive if you're used to how some other languages do it (and not if you're used to some others), and worth knowing.

Here are some examples of this not referring to an object in ES5's strict mode:

(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);
    }
})();

Output:

[Strict] direct; typeof this = undefined
[Strict] with 5; typeof this = number
[Strict] with true; typeof this = boolean
[Strict] with 'hi'; typeof this = string

Whereas in loose mode, all of those would have said typeof this = object; live copy.

这篇关于“this"是什么意思?在 jQuery 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆