Javascript jQuery 中的“this”是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4195970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does "this" mean in jQuery?
提问by JCm
In jquery, what does this
means and when it is used?
在 jquery 中,什么this
意思以及何时使用?
回答by T.J. Crowder
this
in JavaScript is very special and powerful. It can mean just about anything. I cover some of it hereand here, but it's really worth finding a good tutorial on JavaScript and spending some time with it.
this
在 JavaScript 中是非常特殊和强大的。它可以意味着任何事情。我在这里和这里介绍了其中的一些内容,但是找到一个关于 JavaScript 的好教程并花一些时间来学习它真的很值得。
Let's look at jQuery's use of it first, then talk about it more generally in JavaScript (a bit).
我们先来看看 jQuery 对它的使用,然后在 JavaScript 中更一般地谈论它(有点)。
In jQuery, specifically
在 jQuery 中,特别是
In code written with jQuery, this
usuallyrefers to the DOM element that's the subject of the function being called (for instance, in an event callback).
在用 jQuery 编写的代码中,this
通常指的是作为被调用函数主题的 DOM 元素(例如,在事件回调中)。
Example jQuery event callback (what this
is is covered in the .bind
docs):
示例 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();
});
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:
类似地,作用于当前 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;
});
Another place jQuery uses this
is in the callback on jQuery.each
:
jQuery 使用的另一个地方this
是在回调中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
.
...这将提醒“一”,然后是“二”,然后是“三”。如您所见,这是完全不同的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 docsfor 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 differentuse of this
by jQuery.)
(令人困惑的是,jQuery 有两个称为each
的函数,上面的一个在 jQuery/$ 函数本身上并且总是以这种方式调用 [jQuery.each(...)
或$.each(...)
],另一个在 jQuery实例[对象] 上而不是 jQuery/$ 函数本身。这里是另一个的文档,我不会在这个答案中讨论另一个,因为它使用this
相同的方式html
和事件回调,我想展示jQuery的不同用法this
。)
Generically in JavaScript
一般在 JavaScript 中
Update:As of ES5's strict mode, that's no longer true, this
refers to an object.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:
更新:从 ES5 的严格模式开始,这不再正确,this
指一个对象。this
可以有任何价值。的值this
任意给定的函数调用内由下式确定的函数是如何被调用(不其中函数被定义,如在如C#或Java语言)。this
调用函数时最常见的设置方法是通过对象上的属性调用函数:
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:
在那里,因为我们叫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"
In fact, foo
isn't intrinsically tied to anyobject at all:
事实上,foo
根本不与任何对象绑定:
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.
在那里,因为我们没有f
通过对象属性调用,所以this
没有明确设置。当this
未明确设置时,它默认为全局对象(window
在浏览器中)。window
可能没有属性firstName
,所以我们的警报中出现了“未定义”。
There are other ways to call functions and set what this
is: By using the function's .call
and .apply
functions:
还有其他方法可以调用函数并设置什么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"
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.
call
设置this
为您给它的第一个参数,然后将您给它的任何其他参数传递给它正在调用的函数。
apply
does exactly the same thing, but you give it the arguments for the function as an array instead of individually:
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`
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.
不过,this
JavaScript 中还有很多值得探索的地方。这个概念很强大,如果你习惯了其他一些语言的做法(而不是如果你习惯了其他语言),那么它有点具有欺骗性,并且值得了解。
Here are some examples of this
not referring to an object in ES5's strict mode:
下面是一些this
在 ES5 的严格模式下不引用对象的例子:
(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.
而在宽松模式下,所有这些都会说typeof this = object
;现场副本。
回答by Naresh Kumar
The this Keyword
这个关键字
In JavaScript, the thing called this, is the object that "owns" the JavaScript code.
在 JavaScript 中,所谓的 this 是“拥有”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.
当在函数中使用时,this 的值是“拥有”该函数的对象。当在对象中使用时,this 的值是对象本身。对象构造函数中的 this 关键字没有值。它只是新对象的替代。当使用构造函数创建对象时,this 的值将成为新对象。
Note that this is not a variable. It is a keyword. You cannot change the value of this.
请注意,这不是变量。它是一个关键字。您无法更改此值。
回答by ryanwaite28
Here is how i would explain it, simply:
这是我将如何解释它,简单地说:
this
refers to the object
that calledthe function
.
this
指的object
是所谓的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.
bar 对象将 foo 的 log 方法的引用存储到它自己的 log 属性中。现在当 bar 调用它的 log 方法时, this 将指向 bar 因为该方法是由 bar 对象调用的。
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.
这适用于任何其他对象,甚至窗口对象。如果通过全局作用域调用函数,则 this 将指向 window 对象。
by using the bind or call methods of a function, you can explicitly define what the object this
will refer to during execution.
通过使用函数的 bind 或 call 方法,您可以显式定义对象this
在执行期间将引用的内容。
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).
有趣的事实:在 中定义的任何内容global scope
,即顶层/级别,都成为window object
(global scope = window object)的属性。
回答by Richard H
Top Google result for "javascript this": http://www.quirksmode.org/js/this.html
“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."
“在 JavaScript 中,“this”总是指我们正在执行的函数的“所有者”,或者更确切地说,是指函数作为其方法的对象。”
Quirksmode is (generally*) excellent, worth reading the whole article in detail.
Quirksmode(通常*)非常出色,值得详细阅读整篇文章。
*Apparently this statement is not necessarily correct, see T.J. Crowder's comment below.
*显然,此声明不一定正确,请参阅下面的 TJ Crowder 评论。
回答by Ujjwal-Nadhani
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
关键字 this 充当占位符,当该方法在 Java Script 中实际使用时,将引用调用该方法的任何对象
回答by Ali
Regular functions belong to the class that defines these functions and the same object that invokes the function is passed to the function as the fist parameter and function handle it with this
keyword;
常规函数属于定义这些函数的类,调用该函数的对象作为第一个参数传递给函数,函数用this
关键字处理它;
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
对象调用函数
obj.func1 ();
obj.func2 ('A');
In fact, functions at runtime look like the following
实际上,运行时的函数如下所示
var obj = {
p1: 'property 1',
func1 (this) {
return this.p1
},
func2 (this, param) {
return this.p1 + param
}
}
func1 (obj);
func2 (obj, 'A');
With bind
method can create a new function that does not belong to class and can set 'this' parameter with a fixed object;
withbind
方法可以创建一个不属于类的新函数,并且可以使用固定对象设置'this'参数;
this.func1 = this.func1.bind(aObject)
In arrow functions, this
binds to the object that defined the arrow function and that the object passed to the function asthis
parameter.
在箭头函数中,this
绑定到定义箭头函数的对象,并将对象作为this
参数传递给函数。