Fully Understanding the <code>this</code> Keyword

Fully Understanding the this Keyword

Tutorial Details
    • Difficulty: Intermediate
    • Completion Time: 1 Hour

Today’s tutorial comes courtesy of the talented Cody Lindley, from his free ebook: JavaScript Enlightenment. He discusses the confusing this keyword, and the various ways to determine and set its value.

Republished Tutorial

Every few weeks, we revisit some of our reader's favorite posts from throughout the history of the site. This tutorial was first published in July, 2011.


Conceptual Overview of this

When a function is created, a keyword called this is created (behind the scenes), which links to the object in which the function operates. Said another way, this is available to the scope of its function, yet is a reference to the object of which that function is a property/method.

Let’s take a look at this object:

<!DOCTYPE html><html lang="en"><body><script>
var cody = {
  living:true,
  age:23,
  gender:'male',
  getGender:function(){return cody.gender;} 
};

console.log(cody.getGender()); // logs 'male'

</script></body></html>

Notice how inside of the getGender function, we are accessing the gender property using dot notation (e.g cody.gender) on the cody object itself. This can be rewritten using this to access the cody object because this points to the cody object.

<!DOCTYPE html><html lang="en"><body><script>
var cody = {
  living:true,
  age:23,
  gender:'male',
  getGender:function(){return this.gender;} 
};

console.log(cody.getGender()); // logs 'male'

</script></body></html>

The this used in this.gender simply refers to the cody object on which the function is
operating.

The topic of this can be confusing, but it does not have to be. Just remember that, in general, this is used inside of functions to refer to the object the function is contained within, as opposed to the function itself (exceptions include using the new keyword or call() and apply()).

Important Notes

  • The keyword this looks and acts like any other variable, except you can’t modify it.
  • – As opposed to arguments and any parameters sent to the function, this is a keyword (not a property) in the call/activation object.

How is the Value of this Determined?

The value of this, passed to all functions, is based on the context in which the function is called at runtime. Pay attention here, because this is one of those quirks you just need to memorize.

The myObject object in the code below is given a property called sayFoo, which points to the sayFoo function. When the sayFoo function is called from the global scope, this refers to the window object. When it is called as a method of myObject, this refers to myObject.

Since myObject has a property named foo, that property is used.

<!DOCTYPE html><html lang="en"><body><script>

var foo = 'foo';
var myObject = {foo: 'I am myObject.foo'};

var sayFoo = function() {
  console.log(this['foo']); 
};

// give myObject a sayFoo property and have it point to sayFoo function
myObject.sayFoo = sayFoo;
myObject.sayFoo(); // logs 'I am myObject.foo' 12

sayFoo(); // logs 'foo'

</script></body></html>

Clearly, the value of this is based on the context in which the function is being called. Consider that both myObject.sayFoo and sayFoo point to the same function. However, depending upon where (i.e. the context) sayFoo() is called from, the value of this is different.

If it helps, here is the same code with the head object (i.e window) explicitly used.

<!DOCTYPE html><html lang="en"><body><script>

window.foo = 'foo';
window.myObject = {foo: 'I am myObject.foo'};
window.sayFoo = function() { ! console.log(this.foo); };
window.myObject.sayFoo = window.sayFoo;
window.myObject.sayFoo();
window.sayFoo();

</script></body></html>

Make sure that as you pass around functions, or have multiple references to a function, you realize that the value of this will change depending upon the context in which you call the function.

Important Note


The this Keyword Refers to the Head Object in Nested Functions

You might be wondering what happens to this when it is used inside of a function that is contained inside of another function. The bad news is in ECMA 3, this loses its way and refers to the head object (window object in browsers), instead of the object within which the function is defined.


In the code below, this inside of func2 and func3 loses its way and refers not to myObject but instead to the head object.

<!DOCTYPE html><html lang="en"><body><script>

var myObject = {
  func1:function() {
     console.log(this); //logs myObject
     varfunc2=function() {
        console.log(this); //logs window, and will do so from this point on 
        varfunc3=function() {
           console.log(this); //logs window, as it’s the head object
        }();
     }();
  }
};

myObject.func1();

</script></body></html>

The good news is that this will be fixed in ECMAScript 5. For now, you should be aware of this predicament, especially when you start passing functions around as values to other functions.

Consider the code below and what happens when passing an anonymous function to foo.func1. When the anonymous function is called inside of foo.func1 (a function inside of a function) the this value inside of the anonymous function will be a reference to the head object.


<!DOCTYPE html><html lang="en"><body><script>
var foo = {
  func1:function(bar){
    bar(); //logs window, not foo
    console.log(this);//the this keyword here will be a reference to foo object
  }
};

foo.func1(function(){console.log(this)});
</script></body></html>

Now you will never forget: the this value will always be a reference to the head object when its host function is encapsulated inside of another function or invoked within the context of another function (again, this is fixed in ECMAScript 5).


Working Around the Nested Function Issue

So that the this value does not get lost, you can simply use the scope chain to keep a reference to this in the parent function. The code below demonstrates how, using a variable called that, and leveraging its scope, we can keep better track of function context.

<!DOCTYPE html><html lang="en"><body><script>

var myObject = {
  myProperty:'Icanseethelight', 
    myMethod:function() {
	var that=this; //store a reference to this (i.e.myObject) in myMethod scope varhelperFunctionfunction(){//childfunction
	var helperFunction function() { //childfunction
	   //logs 'I can see the light' via scope chain because that=this
           console.log(that.myProperty); //logs 'I can see the light'
           console.log(this); // logs window object, if we don't use "that"
        }();
    }
}

myObject.myMethod(); // invoke myMethod

</script></body></html>

Controlling the Value of this

The value of this is normally determined from the context in which a function is called (except when the new keyword is used – more about that in a minute), but you can overwrite/control the value of this using apply() or call() to define what object this points to when invoking a function. Using these methods is like saying: “Hey, call X function but tell the function to use Z object as the value for this.” By doing so, the default way in which JavaScript determines the value of this is overridden.

Below, we create an object and a function. We then invoke the function via call() so that the value of this inside the function uses myObject as its context. The statements inside the myFunction function will then populate myObject with properties instead of populating the head object. We have altered the object to which this (inside of myFunction) refers.

<!DOCTYPE html><html lang="en"><body><script>

var myObject = {};

var myFunction = function(param1, param2) {
  //setviacall()'this'points to my Object when function is invoked
  this.foo = param1;
  this.bar = param2;
  console.log(this); //logs Object{foo = 'foo', bar = 'bar'}
};

myFunction.call(myObject, 'foo', 'bar'); // invoke function, set this value to myObject

console.log(myObject) // logs Object {foo = 'foo', bar = 'bar'}

</script></body></html>

In the example above, we are using call(), but apply() could be used as well. The difference between the two is how the parameters for the function are passed. Using call(), the parameters are just comma separated values. Using apply(), the parameter values are passed inside of an array. Below, is the same idea, but using apply().

<!DOCTYPE html><html lang="en"><body><script>

var myObject = {};

var myFunction = function(param1, param2) {
  //set via apply(), this points to my Object when function is invoked 
  this.foo=param1;
  this.bar=param2;
  console.log(this); // logs Object{foo='foo', bar='bar'}
};

myFunction.apply(myObject, ['foo', 'bar']); // invoke function, set this value
console.log(myObject); // logs Object {foo = 'foo', bar = 'bar'}

</script></body></html>

What you need to take away here is that you can override the default way in which JavaScript determines the value of this in a function’s scope.


Using the this Keyword Inside a User-Defined Constructor Function

When a function is invoked with the new keyword, the value of this — as it’s stated in the constructor — refers to the instance itself. Said another way: in the constructor function, we can leverage the object via this before the object is actually created. In this case, the default value of this changes in a way not unlike using call() or apply().

Below, we set up a Person constructor function that uses this to reference an object being created. When an instance of Person is created, this.name will reference the newly created object and place a property called name in the new object with a value from the parameter (name) passed to the constructor function.

<!DOCTYPE html><html lang="en"><body><script>

var Person = function(name) {
  this.name = name || 'johndoe'; // this will refer to the instanc ecreated 
}

var cody = new Person('Cody Lindley'); // create an instance, based on Person constructor

console.log(cody.name); // logs 'Cody Lindley'

</script></body></html>

Again, this refers to the “object that is to be” when the constructor function is invoked using the new keyword. Had we not used the new keyword, the value of this would be the context in which Person is invoked — in this case the head object. Let’s examine this scenario.

<!DOCTYPE html><html lang="en"><body><script>

var Person = function(name) {
  this.name=name||'johndoe'; 
}

var cody = Person('Cody Lindley'); // notice we did not use 'new'
console.log(cody.name); // undefined, the value is actually set at window.name
console.log(window.name); // logs 'Cody Lindley'

</script></body></html>

The Keyword this Inside a Prototype Method Refers to a Constructor instance

When used in functions added to a constructor’s prototype property, this refers to the instance on which the method is invoked. Say we have a custom Person() constructor function. As a parameter, it requires the person’s full name. In case we need to access the full name of the person, we add a whatIsMyFullName method to the Person.prototype, so that all Person instances inherit the method. When using this, the method can refer to the instance invoking it (and thus its properties).

Here I demonstrate the creation of two Person objects (cody and lisa) and the inherited whatIsMyFullName method that contains the this keyword to access the instance.

<!DOCTYPE html><html lang="en"><body><script>

var Person = function(x){
    if(x){this.fullName = x};
};

Person.prototype.whatIsMyFullName = function() {
    return this.fullName; // 'this' refers to the instance created from Person()
}

var cody = new Person('cody lindley');
var lisa = new Person('lisa lindley');

// call the inherited whatIsMyFullName method, which uses this to refer to the instance
console.log(cody.whatIsMyFullName(), lisa.whatIsMyFullName());

/* The prototype chain is still in effect, so if the instance does not have a 
fullName property, it will look for it in the prototype chain. 
Below, we add a fullName property to both the Person prototype and the Object 
prototype. See notes. */

Object.prototype.fullName = 'John Doe';
var john = new Person(); // no argument is passed so fullName is not added to instance
console.log(john.whatIsMyFullName()); // logs 'John Doe'

</script></body></html>

The take away here is that the keyword this is used to refer to instances when used inside of a method contained in the prototype object. If the instance does not contain the property, the prototype lookup begins.

Notes

- If the instance or the object pointed to by this does not contain the property being referenced, the same rules that apply to any property lookup get applied and the property will be “looked up” on the prototype chain. So in our example, if the fullName property was not contained within our instance then fullName would be looked for at Person.prototype.fullName then Object.prototype.fullName.


Read the Book for Free!

JavaScript Enlightenment

This book is not about JavaScript design patterns or implementing an object-oriented paradigm with JavaScript code. It was not written to distinguish the good features of the JavaScript language from the bad. It is not meant to be a complete reference guide. It is not targeted at people new to programming or those completely new to JavaScript. Nor is this a cookbook of JavaScript recipes. Those books have been written.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Stoian Kirov

    Is it the same in PHP?

    • http://my.opera.com/patkoscsaba/blog Patkos Csaba

      In PHP it’s more simple. $this always refers to an instance of the current class. You can use it in all the methods inside the class. However, please note, $this can not be used in closures (anonymous functions) in PHP, at least not in the latest 5.4 and older versions.

      • http://inkwell.dotink.org Matthew J. Sahagian

        `$this` can be used in anonymous functions — but it does not reference the function, rather whatever `$this` was in the parent scope. It’s an “automatic” `use`.

        class Foo
        {
        public function __construct()
        {
        $this->bar = ‘FooBar’;
        }

        public function gibberish()
        {
        call_user_func(function(){ echo $this->bar; });
        }
        }

        $foo = new Foo();
        $foo->gibberish();

        5.4+ only as far as I know.

  • luka Cosic

    nice tutorial,

    you made a mistake of this bit of code:

    {returncody.gender;}

    it should have a space as so:

    {return cody.gender;}

    otherwise it would execute correctly

    • Alchemication

      Hahaha, terrible mistake, not forgiving you that……Never! ;]

  • http://imkevinxu.com Kevin

    Reading about the nested functions made me feel like inception lol. Really great piece!

    • Karina

      :) funny

      • http://net.tutsplus.com/tutorials/javascript-ajax/fully-understanding-the-this-keyword/ JUSTIN

        Not that much :)

  • http://ecustom Lucas

    4 Javascrip related articles in a row. Nice!

  • Zach

    Great excerpt!

    Really well-written, and a helpful topic to choose.

    Definitely thinking about investing in the full version.

  • http://log.egamal.com Gamal

    Excuse me Cody, this question may sound off-topic but could you tell me what’s the picture on the book cover ?

    Thank you :)

  • http://massimple.es Jose

    Excelent tutorial!!

    I will definetly buy the book. That was exactly what I was looking for to improve my JS skills!!

    Thanks for posting this!!

  • http://twitter.com/_chrisjacob Chris Jacob

    Excellent explanation. I finally get it! Thank You!

    This will do well to promote your book… I’m also thinking of purchasing ^_^

    I think there are a few typo’s / formatting issues in some of the code examples – perhaps when being published on nettuts… would like the author to review the code snippets just incase.

    Thanks again!

    • http://www.codylindley.com cody lindley

      All of the code examples have been tested and run in JSFiddle without error.

      • Sh.Gamble

        I get error in firefox for the nested function example:

        var myObject = {
        myProperty:’Icanseethelight’,
        myMethod:function() {
        var that=this; //store a reference to this (i.e.myObject) in myMethod scope varhelperFunctionfunction(){//childfunction
        var helperFunction function() { //childfunction
        //logs ‘I can see the light’ via scope chain because that=this
        console.log(that.myProperty); //logs ‘I can see the light’
        console.log(this); // logs window object, if we don’t use “that”
        }();
        }
        }

        myObject.myMethod(); // invoke myMethod

  • http://www.aaareplicamall.com high replica watches

    In fact,it’s a little difficult for me to understand.

    But I found its benefits in the end.

    A really good tutorial!

  • http://barisvelioglu.net Barış V.

    I have some confusion about ‘this’ keyword. Now its more clear for me

    Thanks

  • John Doe

    This is Great tutorial !

    you made some things clear,

    BUT , wtf does ARABIC typography have to do with JavaScript ?

    I am talking about the book cover in case you didn’t guess. it’s stupid and irrelevant

    Did someone actually bought that book ,with that stupid cover ?

    I don’t think so.

    Take close look at pics here.

    http://en.wikipedia.org/wiki/Allah

    I know you know what we all know ! :D

    • John Doe

      Hi , sorry ,I MUST respect others beliefs , its just an ART , I shouldn’t say these words
      I am really sorry .
      could you please delete my comment above , sorry again :(

      • John Doe

        I do respect others believes.

        That’s why I said it’s irreverent.

        do you know how to read what you called art ?

        if you know , you wouldn’t be using those words as a javascript book cover.

    • ashraf

      I don’t know what it reads, Yes its Arabic but no need to freak out.

      We have seen and used -Lorem ipsum dolor sit amet, consectetur adipisicing elit,…..

      Is it Spanish? Portuguese? Its just not relevant, so we just don’t care

      Its looks like calligraphic art and it looks good, might be out of place but who cares.

      The book and tutorial are very good and thats all matters.

  • amel almgdmi

    hi great tut

    i just i want to say im a muslim and i hope you john didnt anything outside the road
    thanx for the nice article again

    • hank

      YO MOMMA

  • http://coderbay.com Coderbay

    Nice explanation of this keyword. thnks

  • Bob de Ruiter

    I don’t think you can explain the this keyword without explaining OOP. Nobody doesn’t know about the this keyword and does know about OOP.

  • kareem

    thank you cody

  • http://www.creativesoapbox.com Kelly Packer

    This is a great teaser chapter – messing around with the code examples really helps me understand the concepts.

    I think I found a few issues in the example for “Working Around the Nested Function Issue”:
    1) there needs to be a equals sign after helperFunction
    2) In the comment on line 6 – I think everything after scope should be deleted.

    I am interested in reading the rest of the book. Thanks.

  • http://koftunka.com Oleksiy

    Very nice tutorial, very helpful.

    Just wanted to add on the “How is the Value of this Determined?” section code:

    var foo = ‘foo’;
    var sayFoo = function() {
    console.log(this['foo']);
    };
    sayFoo(); // returns ‘undefined’

    because var foo is not a property of global object, equally call window.foo will return ‘undefined’.
    In order for this example to work var foo should be defined without ‘var’:

    foo = ‘foo’;

    sayFoo(); // ‘foo’

    • https://plus.google.com/112996405685462096342 maksimr

      @Oleksiy you are not right.

      ‘var foo’ will also become the property of the global object ( if it defined in global scope ) but with some different properties, so the code above is correct.

  • http://www.nomad-one.com nomadone

    Hi Cody. Looks like a really nice book.

    I think you should change the cover pic though. It seems to contain Arabic verses from the Quran and in one part a piece of the name of Allah which would offend muslims for the use you have used it for. If anyone who does’t understand the etiquette of using verses of the Quran prints they could inadvertantly violate certain rules with how Quranic verses should be treated.

    Hope the advice helps.

    Where di you find the pic?

    To John Doe, it’s not ART, but text from our scripture which Muslims hold sacred and as such should not be treated as mere visual.

    Anyway, it’s obviously just a mistake by the author but I think it’s worth looking at and changing or you’re sure to offend some people.

    • Coder

      Usually I don’t like off topic comments, but I have to say it now. I think it’s better to use an image of Arabic calligraphy (I understand the reason why it’s in the book!) that doesn’t contain any religious words. It’s hard to say when I look at that shot (it’s a partial shot and difficult to read), but it looks like it refers to a religious text.

      • http://www.amrabdelaziz.com 4amrabdelaziz

        You are wrong because they contain religious words, plz change the pic . plz

      • Coder

        @4amrabdelaziz: Read my comment again. Saying ‘You are wrong’ while I said that it might be a religious text, doesn’t make sense.

  • http://danneu.com danneu

    I’ve been writing Javascript for a few months now and this is the first tutorial that gave us a bunch of minimal examples just to get the point across with only slight code modifications between the examples. Thanks for that. It’s much easier to internalize something like `this` when I can just see a bunch of cases at once.

  • Andy

    The similar article was published here few days ago, http://blog.jiyala.com/understanding-this-in-javascript/

  • https://plus.google.com/112996405685462096342 maksimr

    @Cody Lindley Thanks for the great article,

    but I have to disagree with some things. For example, when you create a function you do not set any value to special keyword ‘this’. Value of ‘this’ depends on the specific type of ‘Reference’ which is not available to developer but used in specification to explain certain structures in JavaScript. This intermediate type appears when accessing the property and it determines the value of ‘this’.

    I strongly advise you to read this article http://dmitrysoshnikov.com/ecmascript/chapter-3-this/.

    With best wishes!

    Maksim.

  • https://twitter.com/affashbasha affash

    This person or (the author) IS Christian fanatic hates the ISLAM and beliefs

    • http://roadha.us haliphax

      Um… it’s a photo of a LANGUAGE, on the cover of a book about a programming LANGUAGE. Get over yourself and quit actively seeking controversy where there is none.

  • http://www.dynamicguru.com Dynamic Guru

    Nice article…
    but I too fail to make a connection between the content of this article and the arabic typography cover :/

  • Alex

    Cody, very well done explaining the concept. Thank you and congrats! However, I agree with others, the selection of the book cover is immoral.

  • Ayoub M.

    I am a Muslim and I don’t think that the cover offending at all. Yes it has a religious meaning and yes it is artistic and if someone like the artistic part of it then it is OK by me. And what has the Animals on O’Reilly’s books covers has to do with content ??? Just get over it.

  • http://www.augustview.com/ Lannon

    Thanks, I was looking all over the net for some information on this topic, very well laid out! I think viewers are more concerned about your book cover ;)

  • http://tormahiri.weebly.com tormahiri

    thanks for article,nice work today
    i am muslim ,all others here ,jus only doing jealous ,don’t care

  • Amador Cuenca

    Excelent! Thanks for the post. I always get confused with the this keyword.

  • http://www.facebook.com/mbriedis Mārtiņš Briedis

    This is all kinda` confusing…

  • http://twitter.com/dnuske Daniel Nuske

    javascript is sick. thanks for the health kit!

  • Some dude

    “Just remember that, in general, this is used inside of functions to refer to the object the function is contained within, as opposed to the function itself…”

    That is possibly the most succinct and practical explanation of “this” I’ve read. Excellent tutorial on an important topic.

  • BUSINESS ANALYST JOBS

    hi i like your
    post.you share good and meaningfull information in this post. really thanks
    BUSINESS ANALYST JOBS

  • Moooddy

    Best post I have ever read about this keyword. Nice work… keep it up!!

  • tiryakioyun

    very good information thanks http://www.tiryakioyun.com