JavaScript Tutorial: A confusing keyword this

Source: Internet
Author: User
Tags anonymous object constructor contains functions variables variable window

Article Introduction: discusses the confusing keyword this, and how to determine and set the value of this.

Today's tutorials come from a new book by Cody Lindley, the "JavaScript Initiation Tutorial/JavaScript Enlightenment". He discussed the confusing keyword this, as well as the method of determining and setting the value of this.

Conceptual Overview this
When a function is created, a keyword This is then created (in the background), which is linked to an object, and the function is manipulated in this object. In other words, the keyword This can be used in a function, a reference to an object, and a function is the property or method of that object.

Let's look at this object:
    1. <! DOCTYPE html>
    2. var cody = {
    3. Living:true,
    4. Age:23,
    5. Gender: ' Male ',
    6. Getgender:function () {return cody.gender;}
    7. };

    8. Console.log (Cody.getgender ()); Logs ' Male '

    9. </script></body>

Notice that in the function Getgender, because inside the Cody object, we can get the gender property (that is, Cody.gender). You can also use this to get the Cody object, because this is the point to the Cody object.
    1. <! DOCTYPE html>
    2. var cody = {
    3. Living:true,
    4. Age:23,
    5. Gender: ' Male ',
    6. Getgender:function () {return this.gender;}
    7. };

    8. Console.log (Cody.getgender ()); Logs ' Male '

    9. </script></body>

This.gender this points to the Cody object, and the Getgender function can manipulate the Cody object.
The subject of this may be a bit confusing, but it doesn't have to be. Just remember, usually, this point is the object that contains the function, not the function itself (with the exception of course, such as keyword New or call () and apply ()).

Important Tips

-keyword This is like the other variable, the only difference is that you can't change it.
-Unlike other arguments and variables passed to a function, this is a keyword (not a property) in the object that calls the function.

How do I determine the value of this?

This is passed to all functions, and its value depends on when the function runtime is invoked. Notice here, because this is a very special place you need to remember.
The MyObject object in the following code has a property sayfoo that points to the function Sayfoo. When you call the Sayfoo function in the global domain, this points to the Window object. When MyObject calls a function, this points to MyObject.

Because MyObject has a property called Foo, which is used here.
    1. <! DOCTYPE html>

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

    4. var sayfoo = function () {
    5. Console.log (this[' foo ']);
    6. };

    7. Give MyObject a Sayfoo property and have it point to Sayfoo function
    8. Myobject.sayfoo = Sayfoo;
    9. Myobject.sayfoo (); Logs ' I am ' 12

    10. Sayfoo (); Logs ' Foo '

    11. </script></body>

It is clear that the value of this depends on when the function is invoked. Myobject.sayfoo and Sayfoo both point to the same function, but the Sayfoo () call has different contexts, and this is a different value. Here is a similar code, the Head Object (window) is explicitly used and hopefully useful to you.
    1. <! DOCTYPE html>

    2. = ' Foo ';
    3. Window.myobject = {foo: ' I am '};
    4. Window.sayfoo = function () {! Console.log (;
    5. Window.myObject.sayFoo = Window.sayfoo;
    6. Window.myObject.sayFoo ();
    7. Window.sayfoo ();

    8. </script></body>

Make sure that when you have multiple references pointing to the same function, you know clearly that the value of this is Tiaogan with the different context of the function.

Important Tips

-All variables and parameters except this are in the range of static variables (lexical scope).

Within the embedded function this points to the head object

You might want to know what happens when you use this in a function that is embedded in another function. Unfortunately in ECMA 3, this does not follow the rule, it does not point to the object to which the function belongs, but to the head object (the browser's Window object).

In the following code, this in Func2 and func3 no longer points to the MyObject, but the head object.
    1. <! DOCTYPE html>
    2. var foo = {
    3. Func1:function (BAR) {
    4. Bar (); Logs window, not foo
    5. Console.log (this);//the this keyword would be is a reference to Foo object
    6. }
    7. };

    8. FOO.FUNC1 (function () {Console.log (This)});
    9. </script></body>

However, in ECMAScript 5, this problem will be corrected. Now, you should be aware of this problem, especially when you pass the value of a function to another function.

Look at the following code, pass an anonymous function to FOO.FUNC1, and when the anonymous function is called in FOO.FUNC1 (the function is nested in another function), this will point to the head object in the anonymous function.

Now you will not forget that if the function containing this is in another function, or is called by another function, this value will point to the head object (again, this will be corrected in ECMAScript 5). )

Resolving problems with nested functions

In order for the value of this to not be lost, you can use a scope chain (scope chain) in the parent function to hold the reference to this. In the following code, using a variable called that, we can save the function context better by using its scope.
    1. <! DOCTYPE html>

    2. var myObject = {
    3. MyProperty: ' Icanseethelight ',
    4. Mymethod:function () {
    5. var that=this; Store a reference to this (I.e.myobject) in MyMethod scope varhelperfunctionfunction () {//childfunction
    6. var helperfunction function () {//childfunction
    7. Logs ' I can-light ' via scope chain because that=this
    8. Console.log (That.myproperty); Logs ' I Can the Light '
    9. Console.log (this); Logs Window object, if we don ' t use ' that '
    10. }();
    11. }
    12. }

    13. Myobject.mymethod (); Invoke MyMethod

    14. </script></body>

control the value of this
The value of this is usually dependent on the context of the calling function (unless you use the keyword new, which will be introduced later), but you can use apply () or call () to specify the object that this point points to when triggering a function to change/control the value of this. In both ways, it's like saying, "Hey, call the X function, but let the Z object do the value of this." "To do this, the JavaScript default of this value will be changed."

Next, we create an object and a function, and then we trigger the function by call (), so this in the function is pointing to myojbect. This in the MyFunction function operates MyObject instead of the head object, so we change the object that this point in myfunction.
    1. <! DOCTYPE html>

    2. var myObject = {};

    3. var myfunction = function (param1, param2) {
    4. Setviacall () ' This ' points to my Object when the function is invoked
    5. = param1;
    6. = param2;
    7. Console.log (this); Logs object{foo = ' foo ', bar = ' Bar '}
    8. };

    9. (myObject, ' foo ', ' Bar '); Invoke function, set this value to MyObject

    10. Console.log (MyObject)//logs Object {foo = ' foo ', bar = ' Bar '}

    11. </script></body>

In the above example, we use call (), apply () can also apply to the same use, the difference between the two is how the parameters passed to the function. With call (), the arguments are separated by commas, and the parameters are passed in an array using apply (). The following is the same code, but apply ().
    1. <! DOCTYPE html>

    2. var myObject = {};

    3. var myfunction = function (param1, param2) {
    4. Set via Apply (), this points to me Object when function is invoked
    7. Console.log (this); Logs object{foo= ' foo ', bar= ' bar '}
    8. };

    9. Myfunction.apply (MyObject, [' foo ', ' Bar ']); Invoke function, set this value
    10. Console.log (MyObject); Logs Object {foo = ' foo ', bar = ' Bar '}

    11. </script></body>

Use this in a custom constructor
When the function is triggered with the keyword new, the value of this-because it is declared in the constructor-points to the instance itself. To put it another way: in a constructor, we can use this to specify the object before the object is actually created. It appears that the change of this value is similar to call () or apply ().

Below, we constructed a constructor person,this point to the object that was created. When the object of person is created, this points to the object and places the property name inside the object, which is the value of the parameter (name) passed to the constructor.
    1. <! DOCTYPE html>

    2. var person = function (name) {
    3. = Name ' JohnDoe '; This is refer to the Instanc ecreated
    4. }

    5. var cody = new Person (' Cody Lindley '); Create a instance, based on person constructor

    6. Console.log (; Logs ' Cody Lindley '

    7. </script></body>

Thus, when the constructor is triggered with the keyword new, this points to the object to create. So if we don't use the keyword new,this the value will point to the context that triggers the person--this is the head object. Let's take a look at the following code.
    1. <! DOCTYPE html>

    2. var person = function (name) {
    3. ' JohnDoe ';
    4. }

    5. var cody = person (' Cody Lindley '); Notice we did not use ' new '
    6. Console.log (; Undefined, the value is actually set at
    7. Console.log (; Logs ' Cody Lindley '

    8. </script></body>

This point within the prototype method points to the constructed instance
When a method is used as the prototype property of a constructor, this in this method points to an instance of the triggering method. Here, we have a constructor for person () that requires the full name of the person, in order to get full name. We have added a Whatismyfullname method to the Person.prototype, and all the person instances inherit the method. This in this method points to the instance that triggered the method (and its properties).

I created two person objects (Cody and Lisa) below, and the inherited Whatismyfullname method contains this to point to this instance.
  1. <! DOCTYPE html>

  2. var person = function (x) {
  3. if (x) {this.fullname = x};
  4. };

  5. Person.prototype.whatIsMyFullName = function () {
  6. return this.fullname; ' This ' refers to the instance created from person ()
  7. }

  8. var cody = new Person (' Cody Lindley ');
  9. var Lisa = new Person (' Lisa Lindley ');

  10. Call the inherited Whatismyfullname method, which uses this to refer to the instance
  11. Console.log (Cody.whatismyfullname (), Lisa.whatismyfullname ());

  12. /* The prototype chain is still in effect, so if the instance does not have a
  13. FullName property, it'll look for it in the prototype chain.
  14. Below, we add a FullName property to both the person prototype and the Object
  15. Prototype. I'm here for your notes. */

  16. Object.prototype.fullName = ' John Doe ';
  17. var john = new Person (); No argument is passed so fullName are not added to instance
  18. Console.log (John.whatismyfullname ()); Logs ' John Doe '

  19. </script></body>

Using This,this in a method within a prototype object points to an instance. If the instance does not contain attributes, the prototype lookup begins.

-If this object does not contain the property that you want to find, then the law applicable to any attribute is also applicable here, that is, the property is "looking" along the prototype chain (prototype chain). So in our case, if the instance does not contain the FullName attribute, then fullName looks for Person.prototype.fullName and then Object.prototype.fullName.

Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.