11 Answers
11

I recommend reading Mike West's article Scope in JavaScript (mirror) first. It is an excellent, friendly introduction to the concepts of this and scope chains in JavaScript.

Once you start getting used to this, the rules are actually pretty simple. The ECMAScript Standard defines this as a keyword that "evaluates to the value of the ThisBinding of the current execution context" (§11.1.1). ThisBinding is something that the JavaScript interpreter maintains as it evaluates JavaScript code, like a special CPU register which holds a reference to an object. The interpreter updates the ThisBinding whenever establishing an execution context in one of only three different cases:

Initial global execution context

This is the case for JavaScript code that is evaluated when a <script> element is encountered:

This occurs when calling a function. If a function is called on an object, such as in obj.myMethod() or the equivalent obj["myMethod"](), then ThisBinding is set to the object (obj in the example; §13.2.1). In most other cases, ThisBinding is set to the global object (§10.4.3).

The reason for writing "in most other cases" is because there are eight ECMAScript 5 built-in functions that allow ThisBinding to be specified in the arguments list. These special functions take a so-called thisArg which becomes the ThisBinding when calling the function (§10.4.3).

These special built-in functions are:

Function.prototype.apply( thisArg, argArray )

Function.prototype.call( thisArg [ , arg1 [ , arg2, ... ] ] )

Function.prototype.bind( thisArg [ , arg1 [ , arg2, ... ] ] )

Array.prototype.every( callbackfn [ , thisArg ] )

Array.prototype.some( callbackfn [ , thisArg ] )

Array.prototype.forEach( callbackfn [ , thisArg ] )

Array.prototype.map( callbackfn [ , thisArg ] )

Array.prototype.filter( callbackfn [ , thisArg ] )

In the case of the Function.prototype functions, they are called on a function object, but rather than setting ThisBinding to the function object, ThisBinding is set to the thisArg.

In the case of the Array.prototype functions, the given callbackfn is called in an execution context where ThisBinding is set to thisArg if supplied; otherwise, to the global object.

Those are the rules for plain JavaScript. When you begin using JavaScript libraries (e.g. jQuery), you may find that certain library functions manipulate the value of this. The developers of those JavaScript libraries do this because it tends to support the most common use cases, and users of the library typically find this behavior to be more convenient. When passing callback functions referencing this to library functions, you should refer to the documentation for any guarantees about what the value of this is when the function is called.

If you are wondering how a JavaScript library manipulates the value of this, the library is simply using one of the built-in JavaScript functions accepting a thisArg. You, too, can write your own function taking a callback function and thisArg:

I forgot a special case. When constructing a new object via the new operator, the JavaScript interpreter creates a new, empty object, sets some internal properties, and then calls the constructor function on the new object. Thus, when a function is called in a constructor context, the value of this is the new object that the interpreter created:

@Daniel Trebbien, Simply awesome! Though IMHO, it would be better if your question #2 be rephrased from What is the value of this at line B? to What is the value of this at line B when obj.staticFunction() is executed? because you can still execute myFun() in which case Line B would still evaluate this to Window. Just to make it clearer.
–
supertonskyDec 19 '12 at 7:38

Awesome answer! Very helpful. I have found though that this changes inside of objects and objects inside of objects too, so it's got to be more than those 3 cases, right?
–
Kevin BealApr 2 '13 at 16:35

@KevinBeal: I am not sure what you mean. If you post a jsFiddle, I will take a look.
–
Daniel TrebbienApr 2 '13 at 17:29

@DanielTrebbien I feel a bit silly. I neglected to notice that when I was console.log()-ing this I was inside of a new function which you addressed in your answer. By object, I simply meant an object literal.
–
Kevin BealApr 2 '13 at 18:57

18

"Once you start getting used to this, the rules are actually pretty simple", I LOL'ed. You can only use that phrase if you follow it with, "I have a truly marvelous demonstration of this proposition which this margin is too narrow to contain."
–
Waylon FlinnMay 13 '13 at 13:45

The this keyword behaves differently in JavaScript compared to other language. In Object Oriented languages, the this keyword refers to the current instance of the class. In JavaScript the value of this is determined mostly by the invocation context of function (context.function()) and where it is called.

1. When used in global context

When you use this in global context, it is bound to global object (window in browser)

document.write(this); //[object Window]

When you use this inside a function defined in the global context, this is still bound to global object since the function is actually made a method of global context.

When you use this inside function that is invoked without any context (i.e. not on any object), it is bound to the global object (window in browser)(even if the function is defined inside the object) .

We can try above points with functions too. However there are some differences.

Above we added members to objects using object literal notation. We can add members to functions by using this. to specify them.

Object literal notation creates an instance of object which we can use immediately. With function we may need to first create its instance using new operator.

Also in an object literal approach, we can explicitly add members to already defined object using dot operator. This gets added to the specific instance only. However I have added variable to the function prototype so that it gets reflected in all instances of the function.

Below I tried out all the things that we did with Object and this above, but by first creating function instead of directly writing an object.

These methods allows to write a function once and invoke it in different context. In other words, they allows to specify the value of this which will be used while the function is being executed. They also take any parameters to passed to the original function when it is invoked.

fun.apply(obj1 [, argsArray]) Sets obj1 as the value of this inside fun() and calls fun() passing elements of argsArray as its arguments.

By now the difference between apply, call and bind must have become apparent. apply allows to specify the arguments to function as array-like object i.e. an object with a numeric length property and corresponding non-negative integer properties. Whereas call allows to specify the arguments to the function directly. Both apply and call immediately invokes the function in the specified context and with the specified arguments. On the other hand, bind simply returns the function bound to the specified this value and the arguments. We can capture the reference to this returned function by assigning it to a variable and later we can call it any time.

When you assign function directly to event handlers of an element, use of this directly inside event handling function refers to the corresponding element. Such direct function assignment can be done using addeventListener method or through the traditional event registration methods like onclick.

Similarly, when you use this directly inside the event property (like <button onclick="...this..." >) of the element, it refers to the element.

However use of this indirectly through the other function called inside the event handling function or event property resolves to the global object window.

The same above behavior is achieved when we attach the function to the event handler using Microsoft's Event Registration model method attachEvent. Instead of assigning the function to the event handler (and the thus making the function method of the element), it calls the function on the event (effectively calling it in global context).

This is really nice and more understable
–
articlestackDec 25 '13 at 9:23

"When you use this inside a function defined in the global context, this is still bound to global object since the function is actually made a method of global context." is incorrect. this is set by how a function is called or by bind, not by where it is defined. Calling any function without a base reference ("context") will default this to the global object or remain undefined in strict mode.
–
RobGJun 20 '14 at 1:50

@RobG hmm may be, but I found this on MDN: In this case, the value of this is not set by the call. Since the code is not in strict mode, the value of this must always be an object so it defaults to the global object. And in fact thats why I thought we can directly make call window.f1(), so that means f1() is already attached to window object, I mean before invocation. Am I getting it wrong?
–
Mahesha999Jun 20 '14 at 19:07

I was commenting (perhaps not clearly) on your linking the setting of this with "the function is actually made a method of the global context", as if it's sort of called window.fn, which it isn't. this defaults to the global object because no base reference was used in the call, not because of where the function is defined (so this is still set by how the function was called). If you explicitly call it using window.fn, then you are setting this to window. Same result, different way of going about it. :-)
–
RobGJun 21 '14 at 3:01

This is a very comprehensive answer with many details about this covered. SO should be full of this kind of answers.
–
NipsAug 2 '14 at 16:05

"this" is all about scope. Every function has its 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:

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.
–
arunjitsinghJul 4 '10 at 16:49

7

The this keyword has nothing to do with scope. Also, it has a meaning also in functions that are not properties of objects.
–
BergiDec 8 '12 at 20:59

@arunjitsingh—there are two schools of thought on that. I like the one that says "everything is an object, but some can be represented by primitives for convenience". ;-)
–
RobGJan 6 at 23:20

Javascript's this

Simple function invocation

Note that we are running this in the normal mode, i.e. strict mode is not used.

When run in a browser, the value of this would be logged as window. This is because window is the global variable in a web browser's scope.

If you run this same piece of code in an environment like node.js, this would refer to the global variable in your app.

Now if we run this in strict mode by adding the statement "use strict"; to the beginning of the function declaration, this would no longer refer to the global variable in either of the envirnoments. This is done to avoid confusions in the strict mode. this would, in this case just log undefined, because that is what it is, it is not defined.

In the following cases, we would see how to manipulate the value of this.

Calling a function on an object

There are different ways to do this. If you have called native methods in Javascript like forEach and slice, you should already know that the this variable in that case refers to the Object on which you called that function (Note that in javascript, just about everything is an Object, including Arrays and Functions). Take the following code for example.

If an Object contains a property which holds a Function, the property is called a method. This method, when called, will always have it's this variable set to the Object it is associated with. This is true for both strict and non-strict modes.

Note that if a method is stored (or rather, copied) in another variable, the reference to this is no longer preserved in the new variable. For example:

// continuing with the previous code snippet
var myVar = myObj.thisMethod;
myVar();
// logs either of window/global/undefined based on mode of operation

Considering a more commonly practical scenario:

var el = document.getElementById('idOfEl');
el.addEventListener('click', function() { console.log(this) });
// the function called by addEventListener contains this as the reference to the element
// so clicking on our element would log that element itself

How does this work? Well, let's see what happens when we use the new keyword.

Calling the function with the new keyword would immediately initialze an Object of type Person.

The constructor of this Object has its constructor set to Person. Also, note that typeof awal would return Object only.

This new Object would be assigned the protoype of Person.prototype. This means that any method or property in the Person prototype would be available to all instances of Person, including awal.

The function Person itself is now invoked; this being a reference to the newly constructed object awal.

Pretty straighforward, eh?

Note that the official ECMAScript spec no where states that such types of functions are actual constructor functions. They are just normal functions, and new can be used on any function. It's just that we use them as such, and so we call them as such only.

Calling functions on Functions : call and apply

So yeah, since functions are also Objects (and in-fact first class variables in Javascript), even functions have methods which are... well, functions themselved.

All functions inherit from the global Function, and two of its many methods are call and apply, and both can be used to manipulate the value of this in the function on which they are called.

This is a typical example of using call. It basically takes the first parameter and sets this in the function foo as a reference to thisArg. All other parameters passed to call are passed to the function foo as arguments.
So the above code will log {myObj: "is cool"}, [1, 2, 3] in the console. Pretty nice way to change the value of this in any function.

apply is almost the same as call accept that it takes only two parameters: thisArg and an array which contains the arguments to be passed to the function. So the above call call can be translated to apply like this:

foo.apply(thisArg, [1,2,3])

Note that call and apply can override the value of this set by dot method invocation we discussed in the second bullet.
Simple enough :)

Presenting.... bind!

bind is a brother of call and apply. It is also a method inherited by all functions from the global Function constructor in Javascript. The difference between bind and call/apply is that both call and apply will actually invoke the function. bind, on the other hand, returns a new function with the thisArg and arguments pre-set. Let's take an example to better understand this:

See the difference between the three? It is subtle, but they are used differently. Like call and apply, bind will also over-ride the value of this set by dot-method invocation.

Also note that neither of these three functions do any change to the original function. call and apply would return the value from freshly constructed functions while bind will return the freshly constructed function itself, ready to be called.

Extra stuff, copy this

Sometimes, you don't like the fact that this changes with scope, specially nested scope. Take a look at the following example.

In the above code, we see that the value of this changed with nested scope, but we wanted the value of this from the original scope. So we 'copied' this to that and used the copy instead of this. Clever, eh?

Why is there a section about the new keyword? Also this question has been beat to death, but we all have "that time we tried to ride the coat-tails of a question answered 4 years ago"
–
JhawinsOct 27 '14 at 15:30

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.
–
PointyJun 27 '10 at 14:34

@pointy thanks. what causes the most confusion about this in js is the fact that in all the languages used earlier (c#, c++), - this can't be manipulated n always points to the object instance whereas in js it depends and can be changed when invoking functions using func.call, func.bind etc. – Sushil
–
SushilJun 25 '13 at 10:04

1

this does not reference a function's scope. this will reference a specific object (or possibly undefined), which as you've said can be changed using .call() or .apply(). A function's scope is (essentially, when simplified) which variables it has access to, and this depends entirely on where the function is declared and cannot be changed.
–
nnnnnnJan 3 at 22:48

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.

+1 Crockford should be the first step in anyone's journey into JS. His book chapters (available for free online) got me on my feet very fast indeed. He goes straight for the crucial bits.
–
Arcane EngineerOct 23 '12 at 23:45

1

Ha, and now Crockford doesn't like this and programs without using it. ;-)
–
RobGJan 6 at 23:21

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.
–
DLehFeb 8 at 22:55

Daniel, awesome explanation! A couple of words on this and good list of this execution context pointer in case of event handlers.

In two words, this in JavaScript points the object from whom (or from whose execution context) the current function was run and it's always read-only, you can't set it anyway (such an attempt will end up with 'Invalid left-hand side in assignment' message.

For event handlers: inline event handlers, such as <element onclick="foo">, override any other handlers attached earlier and before, so be careful and it's better to stay off of inline event delegation at all.
And thanks to Zara Alaverdyan who inspired me to this list of examples through a dissenting debate :)

Since this thread has bumped up, I have compiled few points for readers new to this topic.

How is the value of this determined?

We use this similar to the way we use pronouns in natural languages like English: “John is running fast because he is trying to catch the train.” Instead we could have written “… John is trying to catch the train”.

thisis not assigned a value until an object invokes the function where it is defined. In the global scope, all global variables and functions are defined on the window object. Therefore, this in a global function refers to (and has the value of) the global window object.

When use strict, this in global and in anonymous functions that are not bound to any object holds a value of undefined.

The this keyword is most misunderstood when: 1) we borrow a method that uses this, 2) we assign a method that uses this to a variable, 3) a function that uses this is passed as a callback function, and 4) this is used inside a closure — an inner function. (2)

What holds the future

Defined in ECMA Script 6, arrow-functions adopt the this binding from the
enclosing (function or global) scope.

While arrow-functions provide an alternative to using bind(), it’s important to note that they essentially are disabling the traditional this mechanism in favor of more widely understood lexical scoping. (1)

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)

It would be better to say it's linked "to the current execution context". Except ES6 (draft) changes that with arrow functions, where this is resolved on the outer execution context.
–
RobGJan 6 at 23:29

Above we create 3 variables with same name 'val'. One in global context, one inside obj and the other inside innerMethod of obj. JavaScript resolves identifiers within a particular context by going up the scope chain from local go global.

When line1 is executed, JavaScript establishes an execution context (EC) for the function call, setting this to the object referenced by whatever came before the last ".". so in the last line you can understand that a() was executed in the global context which is the window.