two great articles about THIS in Javascript

来源:互联网 发布:网络分销产品要点分析 编辑:程序博客网 时间:2024/06/05 01:18

点击打开链接Tom Hicks

Some of this

11 AUG 2014

Bjorn Tipling wrote an interesting article about the this keyword in JavaScript. Whilst it did explain lots of the different ways in which this manifests itself, it was incredibly long, and I think approached the explanation from the wrong direction, leading to a very complex explanation of a simple concept.

The problem is that the explanation was based around the question: “what is this for this piece of code that I’ve written?”

The way JavaScript works, the this keyword is not defined at the time you write the code, but at the time you execute it, which makes answering the above question pretty pointless. It is akin to describing how to use a hammer in terms of the types of wood you can join together with it: you can probably come up with a useful list, but it won’t be exhaustive, and it doesn’t help you understand much about hammers.

Whenever I have to explain this to people, I explain it as follows:

  • this is the thing before the dot when a function is called
  • if there is no dot, this is the global object (or undefined in strict mode)
  • if the function has been explicitly bound (using callapply or bind), it trumps either of the above rules
  • if the function is invoked with the new keyword, this refers to an object whose prototype is equal to the function’s prototype property

That’s it.

To go on and explain what jQuery sets this to in its each method, etc. is to describe a library implementation detail. Just to know that it can be defined by a library author is enough - the actual detail should be in that library’s docs.

So I would urge people to try and avoid thinking about this in terms of what other languages do. Although it does work a bit like this in other languages in certain circumstances, it’s a mistake to take that as your starting point, because you then have to have lots of “oh but in X case is does Y” rules in your head.

If you start with the (correct) assumption that this is defined at call-time, not at write-time, it’ll be a whole lot easier to understand.

Tom Hicks

Tom Hicks

11 AUG 2014

点击打开链接

Understand JavaScript’s “this” With Clarity, and Master It

july. 5 2 Years Ago 105

(Also learn all the scenarios when this is most misunderstood.)

Prerequisite: A bit of JavaScript.
Duration: about 40 minutes.

The this keyword in JavaScript confuses new and seasoned JavaScript developers alike. This article aims to elucidate this in its entirety. By the time we make it through this article, this will be one part of JavaScript we never have to worry about again. We will understand how to use thiscorrectly in every scenario, including the ticklish situations where it usually proves most elusive.

Table of Contents

  •  Receive Updates
  •  JavaScript’s this Keyword Basics
  •  The Biggest Gotcha with JavaScript “this” keyword
  •  The use of this in the global scope
  •  When this is most misunderstood and becomes tricky
  •  Fix this when used in a method passed as a callback
  •  Fix this inside closure
  •  Fix this when method is assigned to a variable
  •  Fix this when borrowing methods
  •  Our Course Website Is Now Live

  • Receive Updates


We use this similar to the way we use pronouns in natural languages like English and French. We write, “John is running fast because he is trying to catch the train.” Note the use of the pronoun “he.” We could have written this: “John is running fast because John is trying to catch the train.” We don’t reuse “John” in this manner, for if we do, our family, friends, and colleagues would abandon us. Yes, they would. Well, maybe not your family, but those of us with fair-weather friends and colleagues. In a similar graceful manner, in JavaScript, we use the this keyword as a shortcut, a referent; it refers to an object; that is, the subject in context, or the subject of the executing code. Consider this example:

 var person = { firstName: "Penelope", lastName: "Barrymore"fullName: function () { ​// Notice we use "this" just as we used "he" in the example sentence earlier?:​ console.log(this.firstName + " " + this.lastName); ​// We could have also written this:​​ console.log(person.firstName + " " + person.lastName); } }

If we use person.firstName and person.lastName, as in the last example, our code becomes ambiguous. Consider that there could be another global variable (that we might or might not be aware of) with the name “person.” Then, references to person.firstName could attempt to access the fistName property from the person global variable, and this could lead to difficult-to-debug errors. So we use the “this” keyword not only for aesthetics (i.e., as a referent), but also for precision; its use actually makes our code more unambiguous, just as the pronoun “he” made our sentence more clear. It tells us that we are referring to the specific John at the beginning of the sentence.

Just like the pronoun “he” is used to refer to the antecedent (antecedent is the noun that a pronoun refers to), the this keyword is similarly used to refer to an object that the function (wherethis is used) is bound to. The this keyword not only refers to the object but it also contains the value of the object. Just like the pronoun, this can be thought of as a shortcut (or a reasonably unambiguous substitute) to refer back to the object in context (the “antecedent object”). We will learn more about context later.

JavaScript’s this Keyword Basics

First, know that all functions in JavaScript have properties, just as objects have properties. And when a function executes, it gets the this property—a variable with the value of the object that invokes the function where this is used.

The this reference ALWAYS refers to (and holds the value of) an object—a singular object—and it is usually used inside a function or a method, although it can be used outside a function in the global scope. Note that when we use strict modethis holds the value of undefined in global functions and in anonymous functions that are not bound to any object.

this is used inside a function (let’s say function A) and it contains the value of the object that invokes function A. We need this to access methods and properties of the object that invokes function A, especially since we don’t always know the name of the invoking object, and sometimes there is no name to use to refer to the invoking object. Indeed, this is really just a shortcut reference for the “antecedent object”—the invoking object.

Ruminate on this basic example illustrating the use of this in JavaScript:

 var person = { firstName :"Penelope", lastName :"Barrymore"// Since the "this" keyword is used inside the showFullName method below, and the showFullName method is defined on the person object,​ // "this" will have the value of the person object because the person object will invoke showFullName ()​ showFullName:function () { console.log (this.firstName + " " + this.lastName); } ​ } ​ person.showFullName (); // Penelope Barrymore

And consider this basic jQuery example with of this:

 // A very common piece of jQuery code​ ​ $ ("button").click (function (event) { // $(this) will have the value of the button ($("button")) object​ ​// because the button object invokes the click () method​ console.log ($ (this).prop ("name")); });

I shall expound on the preceding jQuery example: The use of $(this), which is jQuery’s syntax for the this keyword in JavaScript, is used inside an anonymous function, and the anonymous function is executed in the button’s click () method. The reason $(this) is bound to the button object is because the jQuery library binds $(this) to the object that invokes the click method. Therefore, $(this) will have the value of the jQuery button ($(“button”)) object, even though $(this) is defined inside an anonymous function that cannot itself access the “this” variable on the outer function.

Note that the button is a DOM element on the HTML page, and it is also an object; in this case it is a jQuery object because we wrapped it in the jQuery $() function.

UPDATE: the following (“Biggest Gotcha” section) was added a couple of days after I published the article

The Biggest Gotcha with JavaScript “this” keyword

If you understand this one principle of JavaScript’s this, you will understand the “this” keyword with clarity: this is not assigned a value until an object invokes the function where this is defined. Let’s call the function where this is defined the “this Function.”

Even though it appears this refers to the object where it is defined, it is not until an object invokes the this Function that this is actually assigned a value. And the value it is assigned is basedexclusively on the object that invokes the this Functionthis has the value of the invoking object in most circumstances. However, there are a few scenarios where this does not have the value of the invoking object. I touch on those scenarios later.

The use of this in the global scope

In the global scope, when the code is executing in the browser, all global variables and functions are defined on the window object. Therefore, when we use this in a global function, it refers to (and has the value of) the global window object (not in strict mode though, as noted earlier) that is the main container of the entire JavaScript application or web page.

Thus:

 var firstName = "Peter", lastName = "Ally"; ​ function showFullName () { // "this" inside this function will have the value of the window object​ // because the showFullName () function is defined in the global scope, just like the firstName and lastName​ console.log (this.firstName + " " + this.lastName); } ​ var person = { firstName :"Penelope", lastName :"Barrymore"showFullName:function () { // "this" on the line below refers to the person object, because the showFullName function will be invoked by person object.​ console.log (this.firstName + " " + this.lastName); } } ​ showFullName (); // Peter Ally​ ​ // window is the object that all global variables and functions are defined on, hence:​ window.showFullName (); // Peter Ally​ ​ // "this" inside the showFullName () method that is defined inside the person object still refers to the person object, hence:​ person.showFullName (); // Penelope Barrymore

When this is most misunderstood and becomes tricky

The this keyword is most misunderstood when we borrow a method that uses this, when we assign a method that uses this to a variable, when a function that uses this is passed as a callback function, and when this is used inside a closure—an inner function. We will look at each scenario and the solutions for maintaining the proper value of this in each example.

A bit about “Context” before we continue
The context in JavaScript is similar to the subject of a sentence in English: “John is the winner who returned the money.” The subject of the sentence is John, and we can say thecontext of the sentence is John because the focus of the sentence is on him at this particular time in the sentence. Even the “who” pronoun is referring to John, the antecedent. And just like we can use a semicolon to switch the subject of the sentence, we can have an object that is current context and switch the context to another object by invoking the function with another object.

Similarly, in JavaScript code:

 var person = { firstName :"Penelope", lastName :"Barrymore"showFullName:function () { ​// The "context"​ console.log (this.firstName + " " + this.lastName); } } ​ ​// The "context", when invoking showFullName, is the person object, when we invoke the showFullName () method on the person object.​ ​// And the use of "this" inside the showFullName() method has the value of the person object,​ person.showFullName (); // Penelope Barrymore​ ​ ​// If we invoke showFullName with a different object:​ ​var anotherPerson = { firstName :"Rohit", lastName :"Khan"​ }; ​ ​// We can use the apply method to set the "this" value explicitly—more on the apply () method later.​ ​// "this" gets the value of whichever object invokes the "this" Function, hence:​ person.showFullName.apply (anotherPerson); // Rohit Khan​ ​ ​// So the context is now anotherPerson because anotherPerson invoked the person.showFullName () method by virtue of using the apply () method​  

The takeaway is that the object that invokes the this Function is in context, and we can change the context by invoking the this Function with another object; then this new object is in context.

Here are scenarios when the this keyword becomes tricky. The examples include solutions to fix errors with this:

  1. Fix this when used in a method passed as a callback

    Things get a touch hairy when we pass a method (that uses this) as a parameter to be used as a callback function. For example:

     // We have a simple object with a clickHandler method that we want to use when a button on the page is clicked​ var user = { data:[ {name:"T. Woods", age:37}, {name:"P. Mickelson", age:43} ], clickHandler:function (event) { var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1​ ​ // This line is printing a random person's name and age from the data array​ console.log (this.data[randomNum].name + " " + this.data[randomNum].age); } } ​ // The button is wrapped inside a jQuery $ wrapper, so it is now a jQuery object​ // And the output will be undefined because there is no data property on the button object​ $ ("button").click (user.clickHandler); // Cannot read property '0' of undefined

    In the code above, since the button ($(“button”)) is an object on its own, and we are passing the user.clickHandler method to its click() method as a callback, we know that this inside ouruser.clickHandler method will no longer refer to the user object. this will now refer to the object where the user.clickHandler method is executed because this is defined inside the user.clickHandler method. And the object that is invoking user.clickHandler is the button object—user.clickHandler will be executed inside the button object’s click method.

    Note that even though we are calling the clickHandler () method with user.clickHandler (which we have to do, since clickHandler is a method defined on user), the clickHandler () method itself will be executed with the button object as the context to which “this” now refers. So this now refers to is the button ($(“button”)) object.

    At this point, it should be apparent that when the context changes—when we execute a method on some other object than where the object was originally defined, the this keyword no longer refers to the original object where “this” was originally defined, but it now refers to the object that invokes the method where this was defined.

    Solution to fix this when a method is passed as a callback function:
    Since we really want this.data to refer to the data property on the user object, we can use the Bind (), Apply (), or Call () method to specifically set the value of this.

    I have written an exhaustive article, JavaScript’s Apply, Call, and Bind Methods are Essential for JavaScript Professionals, on these methods, including how to use them to set the thisvalue in various misunderstood scenarios. Rather than re-post all the details here, I recommend you read that entire article, which I consider a must read for JavaScript Professionals.

    To fix this problem in the preceding example, we can use the bind method thus:

    Instead of this line:

     $ ("button").click (user.clickHandler);

    We have to bind the clickHandler method to the user object like this:

     $("button").click (user.clickHandler.bind (user)); // P. Mickelson 43

    — View a working example of this on JSBin

  2. Fix this inside closure

    Another instance when this is misunderstood is when we use an inner method (a closure). It is important to take note that closures cannot access the outer function’s this variable by using the this keyword because the this variable is accessible only by the function itself, not by inner functions. For example:

     var user = { tournament:"The Masters", data :[ {name:"T. Woods", age:37}, {name:"P. Mickelson", age:43} ], ​ clickHandler:function () { // the use of this.data here is fine, because "this" refers to the user object, and data is a property on the user object.​ ​ this.data.forEach (function (person) { // But here inside the anonymous function (that we pass to the forEach method), "this" no longer refers to the user object.​ // This inner function cannot access the outer function's "this"​   console.log ("What is This referring to? " + this); //[object Window]​   console.log (person.name + " is playing at " + this.tournament); // T. Woods is playing at undefined​ // P. Mickelson is playing at undefined​ }) } ​ } ​ user.clickHandler(); // What is "this" referring to? [object Window]

    this inside the anonymous function cannot access the outer function’s this, so it is bound to the global window object, when strict mode is not being used.

    Solution to maintain this inside anonymous functions:
    To fix the problem with using this inside the anonymous function passed to the forEachmethod, we use a common practice in JavaScript and set the this value to another variable before we enter the forEach
    method:

     var user = { tournament:"The Masters", data :[ {name:"T. Woods", age:37}, {name:"P. Mickelson", age:43} ], ​ clickHandler:function (event) { // To capture the value of "this" when it refers to the user object, we have to set it to another variable here:​ // We set the value of "this" to theUserObj variable, so we can use it later​ var theUserObj = thisthis.data.forEach (function (person) { // Instead of using this.tournament, we now use theUserObj.tournament​ console.log (person.name + " is playing at " + theUserObj.tournament); }) } ​ } ​ user.clickHandler(); // T. Woods is playing at The Masters​ // P. Mickelson is playing at The Masters

    It is worth noting that many JavaScript developers like to name a variable “that,” as seen below, to set the value of this. The use of the word “that” is very awkward for me, so I try to name the variable a noun that describes which object “this” is referring to, hence my use ofvar theUserObj = this in the preceding code.

     // A common practice amongst JavaScript users is to use this code​ var that = this;

    — View a working example of this on JSBin

  3. Fix this when method is assigned to a variable

    The this value escapes our imagination and is bound to another object, if we assign a method that uses this to a variable. Let’s see how:

     // This data variable is a global variable​ var data = [ {name:"Samantha", age:12}, {name:"Alexis", age:14} ]; ​ var user =// this data variable is a property on the user object​ data :[ {name:"T. Woods", age:37}, {name:"P. Mickelson", age:43} ], showData:function (event) { var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1​ ​ // This line is adding a random person from the data array to the text field​ console.log (this.data[randomNum].name + " " + this.data[randomNum].age); } ​ } ​ // Assign the user.showData to a variable​ var showUserData = user.showData; ​ // When we execute the showUserData function, the values printed to the console are from the global data array, not from the data array in the user object​ //​ showUserData (); // Samantha 12 (from the global data array)​ ​

    Solution for maintaining this when method is assigned to a variable:
    We can fix this problem by specifically setting the this value with the bind method:

     // Bind the showData method to the user object​ var showUserData = user.showData.bind (user); ​ // Now we get the value from the user object, because the <em>this</em> keyword is bound to the user object​ showUserData (); // P. Mickelson 43
  4. Fix this when borrowing methods

    Borrowing methods is a common practice in JavaScript development, and as JavaScript developers, we will certainly encounter this practice time and again. And from time to time, we will engage in this time-saving practice as well. For more on borrowing methods, read my in-depth article, JavaScript’s Apply, Call, and Bind Methods are Essential for JavaScript Professionals.

    Let’s examine the relevance of this in the context of borrowing methods:

     // We have two objects. One of them has a method called avg () that the other doesn't have​ // So we will borrow the (avg()) method​ var gameController = { scores :[20, 34, 55, 46, 77], avgScore:null, players :[ {name:"Tommy", playerID:987, age:23}, {name:"Pau", playerID:87, age:33} ] } ​ var appController = { scores :[900, 845, 809, 950], avgScore:null, avg :function () { ​ var sumOfScores = this.scores.reduce (function (prev, cur, index, array) { return prev + cur; }); ​ this.avgScore = sumOfScores / this.scores.length; } } ​ //If we run the code below,​ // the gameController.avgScore property will be set to the average score from the appController object "scores" array​   // Don't run this code, for it is just for illustration; we want the appController.avgScore to remain null​ gameController.avgScore = appController.avg(); ​

    The avg method’s “this” keyword will not refer to the gameController object, it will refer to the appController object because it is being invoked on the appController.

    Solution for fixing this when borrowing methods:
    To fix the issue and make sure that this inside the appController.avg () method refers to gameController, we can use the apply () method thus:

     ​ // Note that we are using the apply () method, so the 2nd argument has to be an array—the arguments to pass to the appController.avg () method.​ appController.avg.apply (gameController, gameController.scores); ​ // The avgScore property was successfully set on the gameController object, even though we borrowed the avg () method from the appController object​ console.log (gameController.avgScore); // 46.4​ ​ // appController.avgScore is still null; it was not updated, only gameController.avgScore was updated​ console.log (appController.avgScore); // null

    The gameController object borrows the appController’s avg () method. The “this” value inside the appController.avg () method will be set to the gameController object because we pass the gameController object as the first parameter to the apply () method. The first parameter in the apply method always sets the value of “this” explicitly.

    — View a working example of this on JSBin

Final Words

I am hopeful you have learned enough to help you understand the this keyword in JavaScript. Now you have the tools (bind, apply, and call, and setting this to a variable) necessary to conquer JavaScript’s this in every scenario.

As you have learned, this gets a bit troublesome in situations where the original context (wherethis was defined) changes, particularly in callback functions, when invoked with a different object, or when borrowing methods. Always remember that this is assigned the value of the object that invoked the this Function.

Be good. Sleep well. And enjoy coding.

Our Course Website Is Now Live

New UPDATE on April 26 2015

Enrollment for our Career Paths is now open. Enroll soon. Career Path 1: Junior JavaScript Developer is already full (you may still get a spot if you join the wait list now). Also, Career Path 3: Modern Frontend Developer and session 2 (this starts immediately after you complete Career Path 1) of Career Path 5: Modern Fullstack Developer are quickly filling up.https://learn.modern-developer.com

105 Comments

  1. Malwat

    I think I can say i fully understand how JS this now. Good job, Man. Great article.

    • Richard Bovell (Author)

      Great. I am happy to hear that.

  2. JF

    Nice article, very well exposed.
    Thank you !

  3. JCh

    Very nice article, your examples are straightforward, thanks for helping me understand JS better.
    PS the site’s overall design also makes it a breeze to read.

    • Richard Bovell (Author)

      Thanks, JCh, and I’m happy to hear the formatting and the article are helpful.

  4. Jian

    Thanks man, I am a junior JS developer, this helps me to become a pro :)

    • Richard Bovell (Author)

      Sweet!

  5. Julian Kigwana

    Thank you for all your the time and effort in explaining this so clearly, you are a great teacher.
    I am dyslexic and often need to resort to video tutorials to understand such concepts fully. But you make this easy. I shall try to find the time to read the rest of your site.

    • Richard Bovell (Author)

      You made my day, Julian. I am very happy that this post has helped you understand the topic very well. I know how difficult it is sometimes for learn technical stuff.

  6. MHD

    You are Great Developer, I am understand this keyword completely,
    thanks

    • Richard Bovell (Author)

      Thanks, MHD, and it is very encouraging to hear that the article helped you understand JavaScript’s “this.”

  7. Mike

    thanks Richard. This article is just awesome.

  8. MuthuGanapathyNathan

    Really what an explanation. I am seeing to buy book for javascript, but after seeing your blog, I have to rethink my decision. Great Explanation.!!!

    Thank you.

    • Richard Bovell (Author)

      You will likely still need a JS book, but you are correct, I do cover quite a bit of JS topics here on the blog. Thanks for kind words.

  9. CR

    Thanks for the Post! Very interesting and gr8 article!

  10. Nick

    Great article, Richard.

    Noticed one thing in the last example, though:

    appController.avg.apply(gameController, gameController.scores);

    Can be rewritten without the second argument as:

    appController.avg.apply(gameController);

    Since 1) avg() doesn’t take any parameters and 2) avg() doesn’t reference the arguments pseudo array. You’re already referring to the correct this.scores.reduce, anyway.

    • Mike

      Thanks for pointing this out. Makes more sense now.

  11. Santosh Marigowda

    Very good article Thank you for your time and effort.

    • Richard Bovell (Author)

      You got it, Santosh. Thanks.

  12. Sam

    Hi Richard,

    Thanks for your great article! It has helped me a lot to learn javascript.

    When I changed your code sample for callback as following, calling user.clickHandler() in a anonymous callback, it works well.

    $ (“.buttonError”).click (function(event) {
    user.clickHandler();
    }
    ); // undefined

    Can you shed the light how it also works well?

    Thanks in advance!

    • Richard Bovell (Author)

      Excellent question, Sam. You are correct that using an anonymous function inside the jQuery’s click method works correctly.

      The reason it works correctly is because code executed inside the anonymous function is executed in the global scope, not in the scope of the containing function (Not bound to the click() method of the button object). And because the user object invokes the clickHandler() method, the “this” keyword will have the value of the user object. So “this” will correctly get the this.data property inside the user object.

  13. Jason

    Would “this” have to be set with the bind method if, in your example above, you used vanilla JavaScript instead of jQuery?

    • Richard Bovell (Author)

      Hi Jason,
      Can you post the example code from the article to which you are referring? Thanks.

      • Jason

        It’s your example #1 above. It’s not just a jQuery thing – even using regular, plain JavaScript, the browser sets ‘this’ to the element which fires the event. Could this be done with call or apply instead of bind? If so, how?

        • Richard Bovell (Author)

          Yes, you can use the call () or apply () methods instead of bind set “this”. Here is an example:
          user.clickHandler.call (user);

          See the article below for much more examples of setting the “this” value with Call or Apply:
          JavaScript’s Apply, Call, and Bind Methods are Essential for JavaScript Professionals

  14. Shrichand Gupta

    This seems the article I was looking for, Concept to demonstrate THIS is excellent, now I am feeling I understand this. “this” contains value in it of the “invoker” object not of that in which “this” was defined. Great Job !! Thank you very much.

    • Richard Bovell (Author)

      I am very happy to hear that the article has helped you totally understand the “this” concept in JavaScript.

  15. Abhijit Mallik

    Thanks Richard.No words to say.Just speechless.Article is just so much descriptive and well versed which really clarified my doubts .I have been looking for “this keyword” concept but failed but your article is just awesome.

    • Richard Bovell (Author)

      Hello Abhijit,
      You made my day :)

      Thanks for the kind compliment and, most important, I am very happy to hear that the articles are helping you to better understand some of the JavaScript’s core concepts.

  16. yougen

    Hi Richard, I have two question about this:
    1. I have following code, this is the callback case:
    var city = “OuterCity”;

    var myNav = {
    city: ‘InnerCity’,
    goDestination:function(callback){
    callback(this.city);
    }
    }
    myNav.goDestination(function anoy(city){
    console.log(this);
    console.log(“go to “, this.city);
    });

    in the goDestination(), callback is invoked by window(suppose no strict mode)? Actually is window.callback()?

    2. In “Fix this inside closure” part, this.data.forEach(function(){…}), the inner anonymous function context is always global(in browser, namely window?) Suppose we call anonymous function as “callback”, in the forEach, always like window.callback?

    Appreciate for your article.

    • Richard Bovell (Author)

      For number 1:

      var myNav = {
      city: “InnerCity”,
      goDestination:function(callback){
      callback(“The myNav City: ” + this.city);
      }
      }
      myNav.goDestination(function (aCity){
      console.log(“What is this: ” + this);
      console.log(“go to THIS.City: ” + this.city);
      console.log(“Argument Passed to callBack: ” + aCity);
      });

      Here are the results:

      // What is this: [object Window]
      // go to THIS.City: undefined
      // Argument Passed to callBack: The myNav City: InnerCity

      Indeed the anonymous callback function is invoked on the Window object, so “this” is the Windows object. But as you can see in my modified code above, you can get the correct city info from the myNav object by simply allowing the callback to print the parameter to the console.

      2. I don’t think I completely understand your second question, but I think the example in number 1 above will answer it.

      • yougen

        Thanks for your answer, “anonymous callback function is invoked on the Window object”, it has already answer the second question. Sorry for the indistinct question.

  17. Minh Nguyen

    All I want to say is: Awesome work!!!. It helps me so much! Thanks you!

    • Richard Bovell (Author)

      I am always very grateful to receive compliments, so thank you, Minh. And much success to you as you master JavaScript.

  18. Subhan

    Great tuts on this keyword, very good explained and covered almost all scenarios for this that is very common in scale-able and modern JavaScript.

    Thanks a lot for it

  19. Hari

    An excellent article for those who want to learn and master in Javascript.

  20. Sean

    Hey Richard, awesome clarity on using the “this” within Javascript..Quick question, regarding the last example:

    console.log (appController.avgScore); // null

    How can we explicitly use or update the appController object again, to get the property of appController.avgScore, or even start to use “this” again within the appController object. Once we borrow the actual method/or object within it, do we loose access to the “this”/object.. Is there a way to regain/update the “this”/object again… If that makes any sense???.. Thanks

    • Richard Of Stanley (Author)

      HI Sean,
      Since we are just borrowing the appController method, everything remains intact for the appController object. So you can use “this” and access the appController.avgScore property as normal.

      I am not sure I answered your question. Please let me know if I didn’t, and I will try to respond promptly with a follow up.

  21. Andreas C

    I just want to thank you for all the hard work you must have put in to writing these tutorials and articles. I found this blog a couple of days ago and I just got started reading through the material here.

    When I did the Javascript course on Codecademy some time ago I tried to do exactly whats covered in number 3 in this article, using “this” in a method that I assigned to a variable and was confused why it didn’t work. Now I know. :)

  22. John

    I posted a question on stackoverflow regarding this article and specifically how “this” works inside closures. Seems like I am still none the wiser.

    http://stackoverflow.com/questions/20242351/this-inside-a-closure-function

  23. John

    My conclusion is that the points you make in “1. Fix this when used in a method passed as a callback”

    are incorrect.

    See this JSFIDDLE – http://jsfiddle.net/EqHJ7/

    You mention several times that this refers to button object now because button object was the one invoking it. However, you are wrong because this is only referring to button object because jquery automatically binds “this” to button object (using either caal or apply). Otherwise, the “this” would point to the window object since the “this” function is being called by another function (jquery.click) and as we know, nested functions or closures point to window object or undefined (depending on strict mode).

    So your following statements are incorrect.

    “In the code above, since the button ($(“button”)) is an object on its own, and we are passing the user.clickHandler method to its click() method as a callback, we know that this inside our user.clickHandler method will no longer refer to the user object. this will now refer to the object where the user.clickHandler method is executed because this is defined inside the user.clickHandler method. And the object that is invoking user.clickHandler is the button object—user.clickHandler will be executed inside the button object’s click method.

    Note that even though we are calling the clickHandler () method with user.clickHandler (which we have to do, since clickHandler is a method defined on user), the clickHandler () method itself will be executed with the button object as the context to which “this” now refers. So this now refers to is the button ($(“button”)) object.”

  24. Arjun

    In,
    // Note that we are using the apply () method, so the 2nd argument has to be an array—the arguments to pass to the appController.avg () method.
    appController.avg.apply (gameController, gameController.scores);

    I do not understand, Why we need to pass gameController.scores array? It works without it! I tried it on JSbin.

    • Todd

      I was thinking the same thing Arjun. The avg function wasnt requesting arguments.

  25. Chad

    I cannot possibly emphasize enough how excited I am to have found your JS blog. Words simply escape me.

    As a Java Developer, I had been struggling in the world of JavaScript due to the nuances surrounding “this”. The source of my agony was because, in it’s most basic usage, “this” performs how I would have expected; thus, resulting in a false understanding of it. However, that false understanding would be exposed the moment more complex code utilized “this”. In a nutshell, I found myself in a programming paradox where, as it seemed, a piece of code performed one way in one place, yet the exact same piece of code performed completely differently in another place, and I could not understand why. Thanks to your tutorial, not only did my lack of understanding become completely obvious, but it now all “makes sense” – which is priceless and essential attribute for any programmer.

    Your post allowed me to understand this subject more than any other tutorial I have read online, and I simply cannot thank you enough for it. I truly appreciate the time, effort, and your talent in explaining this previously frustrating topic.

  26. zack

    I think this one of the most important and one of the best webpage I’ve ever read in my entire life. I’m almost indebted to you. I have been struggling with this “this” enigma, until it started to unravel before me right here.

  27. angel

    Richard thanks for the article…I’m not pretty sure with the closure case…this would not be a callback to? is a function which is called inside the map method from array object

    why this
    [1,2,3].map(function(x){console.log(this)}) the this is the global or windows while

    while
    $(“buttom”).click(fun …..this….) this is the buttom

    both are pretty similar in structure…why in one ref to global and in the other refers to buttom

    thanks

    • Laker

      Heya, I’m no expert or anything, but from what I’ve read here it’s simply because the first example is plain javascript while the second one is jquery.

      So in the first one you are using anonymous function, which in plain JS (without strict mode) refers to the global, or window object.

      In the second example you are using jquery, which automatically assigns this to jquery object, in this case the button.

      Hope it helps… a year later … :/

  28. tc

    awesome, thanks! just what i needed

  29. Colin

    Great article, but I am a bit confused by the last example. Do you need the second argument to apply? The function doesn’t take any extra paramters, as some other people mentioned.

  30. Binh Thanh Nguyen

    Thanks, nice post

  31. Tarak

    Hats Off to the great teacher “Richard”

  32. froi

    Thank you! Great Article.. very helpful! :)

  33. Johan

    Best javascript article i have ever seen in my life . it’s only you who explained it well or i was stupid !!!! :)

  34. Sunil Gautam

    “this” is this best article on this :).

  35. Bill

    function myFunction(this)
    {
    alert(this.id);
    }

    This is a paragraph.

    Hi, Richard, first of all, I want to thank you for the amazing posts, and second, I have an issue hoping you could help me get this clarified. As you can see the code above, I used an inline event handler with the this keyword, but when I click on the paragraph, it won’t return the id at all nor does anything, can you please help me with this? I am really struggling with event arguments right now, even want to cry :(. Thank you very much in advance Richard

  36. Bill

    function myFunction(this)
    {
    alert(this.id);
    }

    Click on a paragraph. An alert box will alert the element that triggered the event
    .

    for some reason the first comment cut off my code.

  37. bill

    Hi Richard, great article sir, by the way, I saw you mentioned “global function”, could you please tell me how to determine the scope of a function? Thank you very much.

  38. yet

    Thanks for connecting the dots in my understanding of this… One important question, how can you test the value of this if lost as to what invoke it?….

  39. bill

    Great website, keep writing more please.

    Yours:
    var randomNum = ((Math.random () * 2 | 0) + 1) – 1;

    Why not?:
    var randomNum = (Math.random () * 2 | 0);

    Going through everyone of your examples,

  40. Bhargav

    Great article. Great content. Very useful day-to-day practical examples. Keep up the good work.

  41. Yoni

    Great post man! it really helped me get a grip of this

  42. Ordirobo

    Great article! It really helps me get out the mystery of this. Wish to see more!

  43. Seshu Vuggina

    Great article! It really helps me alot

  44. vivek pothagoni

    Great Job!!! I am so confused with ‘this’. After reading the article, I when back to code where I had problem. Easily I was able to fix the problem.

  45. Ranjith Raghavan

    this is a great article. Thanks
    By the way, ever considered teaching grammar to JavaScript devs? :)

  46. mug896

    in last example ” appController.avg.apply (gameController, gameController.scores); ”

    apply() is not needed just bind() enough like this

    appController.avg.bind(gameController)();

  47. Michael

    Hi-

    Judging by the comments, I must be missing something. When I paste the code in the very first example into the console in Firebug and run it, in the console log I get: “undefined” Shouldn’t it be outputting the first and last name twice?

    Thanks,

    Michael

  48. Pavel Demeshchik

    Great article, good job Richard!

  49. TylerF.

    Good article. I don’t think I fully comprehend everything but it is definitely informative.

    • Richard (Author)

      TylerF, Let me know what specifically you don’t understand. I will try to clarity, and I may even add the clarification to the article, so that the article is more comprehensible.

  50. Rafi

    First i read your article on “context of JavaScript” and that was loud and clear and found out that you have other articles on JavaScript and started reading all, all of the are same loud and clear.

  51. Huy Son

    I think I found a mistake for the borrowing methods problem.
    We only need to do :
    appController.avg.apply (gameController);

    Otherwise, the article is great.
    I will read more !

  52. Zim

    Thanks. i have been working (kind of) successfully in the web dev arena for going on 15 years, using javascript in the front end. A good friend/colleague described it as the splatter gun approach. I had no formal training. I am finally beginning to understanding what javascript actually is and how it is put together. I blame ridiculous deadlines for this :)

    It is liberating for me. And these articles are REALLY REALY helping. So just wanted to say thanks for doing this. Big respect for sharing your knowledge

  53. Muddassir

    Hi Richard,

    You are awesome buddy, i learnt most of the fundamental concepts from your tutorials.

    just checking Any update on the new courses, any tentative dates or anything, i am really excited for them.

  54. Venkatesh Kumar

    Guys, Beware before you use any event handlers with bind. You cannot unbind until you have assigned the binded function as callback.
    Check out this link
    http://msdn.microsoft.com/en-in/library/ie/dn741342(v=vs.94).aspx

  55. ritika

    Richard, you are a star!!! extremely helpful and well written concept.

  56. Joynal Abedin

    Awesome article i ever seen.

  57. Joynal Abedin

    Awesome article i ever seen.

  58. Ko

    Where are indentations in the code!! so hard to read

  59. Mahavir

    Awesome Article..!! Worth Reading..!!

  60. Leandro

    Great article and nice read. Thank you.

  61. Gytis

    *this* was a long read.. But very useful :)

  62. kedar parikh

    Great article richard !! very well written, simple language and easy to understand… helped a lot in clearing all the things about this..
    Thanx again :)

  63. Santosh

    Great article. thank you
    Santosh

  64. gheorghe

    I`ve just wrote like that
    appController.avg.apply(gameController);

    and it works without the second parameter, gameController.scores….

    How that?

  65. Jason Dufair

    “Referent” is the target of a reference. “this” is a reference, not a referent.

  66. David

    Great job Richard! After reading this article, I can unequivocally say that I will be reading many of your other posts in the future. I am currently helping a set of students work through “this” and your article will prove an invaluable resource for both myself and the students with whom I work. There is only one change I would posit as a possible improvement. Perhaps within the context of the code snippets, you could indent lines of code to make it explicitly clear where outer functions begin and end. Just a small thought, but overall, your post remains one of the most concise and clear explanations of this traditionally tricky subject. Thanks again!

  67. Mike Joyce

    Excellent article. Your explanations are very clear and easy to understand. Thanks!

  68. Rohit

    Great Tutorial ! It’s very helpful.

    Thanks buddy

  69. Bart Van Audenhove

    Great article!
    I have a question, concerning paragraph “The use of this in the global scope”.
    Do I understand correctly that in the example, the following:

    this.showFullName ();​

    would produce the same result as

    window.showFullName (); // Peter Ally​

    Maybe it would be nice to add this to the example, it would make it even clearer, I think…

  70. Frank Topel

    Thanks alot for your very useful articles! Readability of the source code sections could be greatly improved if you could indent stuff, though. Is that by any means possible?

    Btw, your input fields above this comment field are completely unlabelled (Current Chrome/Win 7).

  71. Vishal

    The Fix this inside closure could have been done by passing this into the forEach method as the thisArg

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach.

Trackbacks for this post

  1. Apply, Call, and Bind Methods are Essential for JavaScript Professionals; Understand Them Well | JavaScript is Sexy
  2. Understand JavaScript’s “this&rdquo...
  3. Understand JavaScript’s “this&rdquo...
  4. 16 JavaScript Concepts JavaScript Professionals Must Know Well | JavaScript is Sexy
  5. Beautiful JavaScript: Easily Create Chainable (Cascading) Methods for Expressiveness | JavaScript is Sexy
  6. this context bind apply call | johngslater
  7. How to Learn JavaScript Properly | JavaScript is Sexy
  8. Anonymous
  9. [FRAGE] Aufruf von Function klappt nicht
  10. How to: JavaScript "this" keyword | SevenNet
  11. Solution: JavaScript "this" keyword #dev #it #computers | Technical information for you
  12. Fixed JavaScript "this" keyword #dev #it #asnwer | Good Answer
  13. Javascript this 关键字 – 剑客|关注科技互联网

Leave a Reply





0 0
原创粉丝点击