The role of this

Source: Internet
Author: User
Document directory
  • Call object Method
  • Constructor
  • Function call
  • Event processing functions
In addition to setting up a scope chain, each running context also provides thisKeyword. Its common usage is, thisAs a unique feature, it provides a way for neighbors to access it. However, relying on this behavior is not reliable: It depends on how we enter the specific circumstances of a particular neighbor, thisIt means everything else. In fact, How do we go to the neighbor's house?It is usually this. There are four situations worth special attention:
  • Call object Method

    In classical object-oriented programming, we need to identify and reference the current object.thisThis role is an excellent role that provides our objects with the ability to find themselves and point to their own attributes.

    <script type="text/javascript">  var deep_thought = {   the_answer: 42,   ask_question: function () {    return this.the_answer;   }  };  var the_meaning = deep_thought.ask_question();</script>

    In this exampledeep_thoughtObject, set its properties the_answerIs 42, andask_questionMethod ). Whendeep_thought.ask_question()During execution, JavaScript creates a runtime context for the function call"."OperatorthisPoint to the referenced object, which isdeep_thoughtThis object. After that, you can usethisFind its own properties in the mirror, and return and save inthis.the_answerValue in: 42.

  • Constructor

    Similarly, when a user is defined as a constructornewFor a function with a keyword,thisIt can be used to reference the newly created object. Let's rewrite an example that reflects this situation:

    <script type="text/javascript">  function BigComputer(answer) {   this.the_answer = answer;   this.ask_question = function () {    return this.the_answer;   }  }  var deep_thought = new BigComputer(42);  var the_meaning = deep_thought.ask_question();</script>

    We compile a function to createBigComputerObject instead of simply creating deep_thoughtObject, andnewKeyword instantiationdeep_thoughtIs an instance variable. Whennew BigComputer()Executed. A new object is created transparently in the background. CallBigComputerAnd itsthisThe keyword is set to point to the reference of the new object. This function can bethisInBigComputerReturns transparently after execution.

    However, you must note thatdeep_thought.the_question()It can still be executed as before. So what happened here? WhythisInthe_questionIs it different from that in bigcomputer? Simply put, we usenewEnterBigComputer, SothisNew object ". On the other hand, we use deep_thoughtEnterthe_questionSo when we execute this method,thisIndicates"deep_thoughtThe referenced object ".thisInstead of reading from the scope chain like other variables, it is based on context and context.Reset.

  • Function call

    If there is no such thing as an object, we call a common function. In this casethisWhat is it?

    <script type="text/javascript">  function test_this() {   return this;  }  var i_wonder_what_this_is = test_this();</script>

    In this case, we do not passnewTo provide context, and do not secretly provide context in the form of an object. Here,thisBy default, reference the most global thing as much as possible: For webpages, this is windowObject.

  • Event processing functions

    The call is more complex than the call of common functions. Assume that we use the function to processonclickEvent. When the event triggers the running of our functionthisWhat is it? Unfortunately, there will be no simple answer to this question.

    If we write an inline event handler,thisReference is globalwindowObject:

    <SCRIPT type = "text/JavaScript"> function click_handler () {alert (this); // pop-up window object} </SCRIPT>... <button id = 'thebutton 'onclick = 'click _ handler () '> click me! </Button>

    However, if we use JavaScript to add event handler functions,thisReferences the DOM element that generates the event. (Note: The event processing here is very simple and easy to read, but the others are quite different. Use the real addevent function instead ):

    <SCRIPT type = "text/JavaScript"> function click_handler () {alert (this); // Dom node for the pop-up button} function addhandler () {document. getelementbyid ('thebutton '). onclick = click_handler;} window. onload = addhandler; </SCRIPT>... <button id = 'thebutton'> click me! </Button>
Complexity

Let's briefly run this final example. We need to askdeep_thoughtOne problem, if not directly runclick_handlerBut by clicking the button, what will happen? The code to solve this problem seems very direct, and we may do this:

<script type="text/javascript"> function BigComputer(answer) {  this.the_answer = answer;  this.ask_question = function () {   alert(this.the_answer);  } } function addhandler() {  var deep_thought = new BigComputer(42),   the_button = document.getElementById('thebutton');  the_button.onclick = deep_thought.ask_question; } window.onload = addhandler;</script>

Perfect, right? Imagine, we click the button,deep_thought.ask_questionExecuted, we also get "42 ". But why does the browser give usundefined? Where are our mistakes?

The problem is obvious:ask_questionA reference is passed and executed as an event processing function, which is not the same as the context for running as an object method. In short,ask_questionIn thisThe keyword points to the DOM element that generates the event, insteadBigComputer. The Dom element does not havethe_answerAttribute, so what we get isundefinedInstead of "42 ″.setTimeoutSimilar behavior occurs when the function execution is delayed and it is in a global context.

This problem occurs from time to time in all corners of the program. If you do not track every corner of the program in detail, it is still very difficult to troubleshoot, especially if your object has DOM elements orwindowWhen the object has an attribute of the same name.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.