views:

179

answers:

7

I have noticed that there doesn’t appear to be a clear explanation of what is the "this" keyword and how it is correctly (and incorrectly used) in JavaScript on the stackoverflow site.

I have witnessed some very strange behaviour with it and have failed to understand why it has occurred.

Would anyone care to explain to me how “this” works and when it should be used?

+2  A: 

Every function in javascript has a scope. Whatever that scope is, is referenced by "this". You can change that scope by doing func.call or func.apply.

By default, and what confuses most beginners, when a callback is called after an event is raised on a DOM element, the scope of the function is the DOM element.

jQuery makes this trivial to change with jQuery.proxy.

blockhead
It's a little more correct to say that every function *call* has a scope. In other words, what's confusing about `this` in Javascript is that it's **not** an intrinsic property of the function itself, but rather an artifact of the way the function is invoked.
Pointy
+3  A: 

I found this when I googled "this" http://www.quirksmode.org/js/this.html

Wai Wong
+11  A: 

You should read this excellent article. It covers the concepts of this and scope chains in a very clear, detailed manner.

Daniel Trebbien
+1  A: 

Whould this help? (Most confusion of 'this' in javascript is coming from the fact that it generally is not linked to your object, but to the current executing scope -- that might not be exactly how it works but is always feels like that to me -- see the article for a complete explanation)

Simon Groenewolt
+1  A: 

"this" is all about scope. Every function has it's own scope, and since everything in JS is an object, even a function can store some values into itself using "this". OOP 101 teaches that "this" is only applicable to instances of an object. Therefore, every-time a function executes, a new "instance" of that function has a new meaning of "this".

Most people get confused when they try to use "this" inside of anonymous closure functions like:

(function(value) {
    this.value = value;
    $('.some-elements').each(function(elt){
        elt.innerHTML = this.value;        // uh oh!! possibly undefined
    });
})(2);

So here, inside each(), "this" doesn't hold the "value" that you expect it to (from

this.value = value;
above it). So, to get over this (no pun intended) problem, a developer could:

(function(value) {
    var self = this;            // small change
    self.value = value;
    $('.some-elements').each(function(elt){
        elt.innerHTML = self.value;        // phew!! == 2 
    });
})(2);

Try it out; you'll begin to like this pattern of programming

arunjitsingh
"everything in JS is an object" is not true, JavaScript also has primitive values, see http://bclary.com/2004/11/07/#a-4.3.2
Marcel Korpel
The primitive values seem to have some methods on themselves, like String#substring(), Number#toString(), etc.. So, maybe not with the same nomenclature as that article, they really behave as if they were objects (they are all prototyped, ie. String#substring() is really: String.prototype.substring = function(){...}). Please correct me if I'm wrong.
arunjitsingh
+1  A: 

It is difficult to get a good grasp of JS, or write more than anything trivial in it, if you don't understand it thoroughly. You cannot just afford to take a quick dip :) I think the best way to get started with JS is to first watch these video lectures by Douglas Crockford - http://yuiblog.com/crockford/, which covers this and that, and everything else about JS.

tathagata