I am currently learning jQuery, and just started implementing "this"
keyword. I understand what it does in jQuery, but does it have the same functionality in javascript, as a scope reference?
Asked
Active
Viewed 181 times
0

FluxEngine
- 12,730
- 14
- 57
- 83
-
Possible duplicates: http://stackoverflow.com/questions/3127429/javascript-this-keyword, http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-javascript-object-literal – levelnis Mar 29 '13 at 21:48
-
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this – Ram Mar 29 '13 at 21:48
3 Answers
3
this
is not some jQuery magic, it is a JavaScript keyword.

Niet the Dark Absol
- 320,036
- 81
- 464
- 592
-
-
Just curious, what exactly can `this` be used for? Sometimes I try to implement it but find that it returns the wrong value/variable/element. – Albert Xing Mar 29 '13 at 21:47
-
while this may not be magic - i think it's pretty magical especially when var that = this; – James Daly Mar 29 '13 at 21:54
1
Yes, this
keyword in JavaScript still means the element in the current scope.

palaѕн
- 72,112
- 17
- 116
- 136
0
Short explanation: this
is the context of a function that can change depending on how that function is called. For example:
function myfunc() {
console.log(this.toString());
}
myfunc(); //=> [object Window]
myfunc.call('Hello World'); //=> Hello World
When using prototypes, this
refers to the current instance. In jQuery it works something like this (very simplified):
(function(win) {
// Constructor
function jQuery(selector) {
}
// Shortcut to create news instances
function $(selector) {
return new jQuery(selector);
}
// Public methods
jQuery.prototype = {
// All methods 'return this' to allow chaining
// 'this' is the jQuery instance
method: function() {
return this;
}
};
win.$ = $; // expose to user
}(window));
So when you do this $(this)
you're just creating a new jQuery instance of whatever this
refers to (usually a DOM element) so you can inherit the prototype and use the public methods.

elclanrs
- 92,861
- 21
- 134
- 171