Understanding JavaScript This value

Source: Internet
Author: User

How to determine the value of this

This value is passed to all functions, and the value of this is based on the context in which the function is called at run time.

For example: When calling the Sayfoo function from a global scope, this references the Window object

When it is called as a method of MyObject, this reference MyObject

 var  foo = "foo"  var  myObject = {foo: "I am Myobject.foo" };  var  Sayfoo = function   () {Console.log ( this  .foo);        };  //  set a MyObject property to Sayfoo and point to the Sayfoo function          Myobject.sayfoo  = Sayfoo; Myobject.sayfoo ();  //  output I am Myobject.foo   Sayfoo ();  //  output foo  

Referencing the head object with the This keyword in a nested function

When this is used inside a nested function, this loses its orientation in ES3, referring to the head object

For example: The This in Func2 and func3 loses direction, not MyObject, but head object

When an anonymous function is called inside a function, the this value inside the anonymous function will be the head object

For example:

var foo = {

Func1:function (BAR) {

Bar (); Output window instead of Foo

Console.log (this); The This keyword here is a reference to the Foo object

}

};

FOO.FUNC1 (function () {

Console.log (this);

});

This value will always be a reference to the head object when this is worthy of being encapsulated within another function or called in the context of another function.

varMyObject ={func1:function() {Console.log ( This);//Output MyObject                varFunc2 =function() {Console.log ( This);//Output window, starting from here, this is the Window object.                     varFUNC3 =function() {Console.log ( This);//Output window, which is the head object                    }();            }();        }        }; Myobject.func1 (); 

Making full use of the scope chain to study nested function problems

You can simply use a scope chain in the parent function to keep a reference to this so that the this value does not

Lost. The following code demonstrates the effective tracking of a function context through that variable and its scope:

Making full use of the scope chain to study nested function problems

varMyObject ={myproperty:"I can see the light", MyMethod:function() {                varthat = This;//MyMethod Scope, save this reference (that is, MyObject)                varHelperfunction =function() {//Child Functions                    //output via scope chain get "I can see the light"Console.log (That.myproperty); Console.log ( This. MyProperty); Console.log ( This);            }();        }        }; Myobject.mymethod ();//Call MyMethod

Use call () or apply () to control this value

This value usually depends on the context of the calling function, but we can override/control this value with apply () or call ()

The difference between call () and apply () is that the function passes the arguments in different ways

If you use Call (), the parameter is just a comma-separated value

If apply () is used, the value of the parameter is passed as an array.

For example, call a function by calling, so that the this value inside the function will myobject as its context

Use call () or apply () to control this value

varMyObject = {}; varMyFunction =function(Parm1, parm2) {//when invoking a function, point this to MyObject by calling ()             This. Foo =Parm1;  This. Bar =Parm2; Console.log ( This);         }; Myfunction.call (MyObject,"foo", "Bar");//Call function, set this value reference to MyObjectConsole.log ("foo=" + Myobject.foo + ", bar=" + Myobject.bar);//loser Foo=foo,bar=bar

Instead, the result of a direct call is:

varMyObject = {}; varMyFunction =function(Parm1, parm2) {//when invoking a function, point this to MyObject by calling ()             This. Foo =Parm1;  This. Bar =Parm2; Console.log ( This);        }; MyFunction ("foo", "Bar");//Direct call, this point to windowConsole.log ("foo=" + Myobject.foo + ", bar=" + Myobject.bar);//foo=undefined,bar=undefinedConsole.log ("foo=" + Myfunction.foo + ", bar=" + Myfunction.bar);//foo=undefined,bar=undefinedConsole.log ("foo=" + foo + ", bar=" + bar);//Foo=foo,bar=bar 

Use the This keyword inside a user-defined constructor

When a function is called with the New keyword, the This value (declared in the constructor) references the instance itself.

For example, the following code creates the person constructor, and when you create an instance of person, this.name references the newly created object.

var function (name) {            this. Name = name | | "John Doe"; // This references the instance that was created         };         var New Person ("Cody Lindley"); // Create an instance based on the person constructor function         Console.log (cody.name); // output Cody Lindley

When the constructor is called with the new keyword, this references the object that is about to be created

If you do not use the New keyword, the This value will be the context in which the person is called-in this case the Head object

The following code:

var function (name) {            this//Thisrefers to the instance created         };         var // Create an instance based on the person constructor function            //newspaper name does not exist, actually the name value is set to Window.name//          Output Cody Lindley

The This keyword in the prototype method references the constructor instance

When this is used in a function added to the prototype property of a constructor, the this reference invokes the instance of the method:

For example:

The This keyword in the prototype method references the constructor instance

 varperson =function(x) {if(x) { This. FullName =x;         }        }; Person.prototype.whatIsMyName=function() {            return  This. fullName;//This refers to the instance created by the person ()        }; varCody =NewPerson ("Cody Lindley"); varLisa =NewPerson ("Lisa Lindley"); //invokes the inherited Whatismyname method, which references the instance with thisConsole.log (Cody.whatismyname (), Lisa.whatismyname ());//output Cody Lindley,lisa LindleyObject.prototype.fullName= "John Doe"; varJohn =NewPerson (); Console.log (John.whatismyname ()); 

This can be used to refer to an instance when the This keyword is used inside a method in a prototype object. If the instance does not contain the property you are looking for, continue to find it on the prototype.

Understanding JavaScript This value

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.