Explanation of this in Javascript

jacklove
Release: 2018-06-11 17:37:17
Original
1862 people have browsed it

The

thisinJavascriptpoints to

beginnerjavascriptEveryone will have a lot of confusion aboutjs#this, such as the following example:

vara ='jack';varobj = {a:'tom',b:function(){console.log(this.a);}};varc = obj.b;c();//Outputjack

##New tojsPeople who may use some other object-oriented languages to understand,think that the output here should betom,, but in fact the output here is Whenjack,But what is the question?And the poster will analyze it step by step.

The commonthispoints injsare divided into4kind:

1.

thisin theobject points to

What isthis in an object,That is, the properties of the object arefunction,andfunctionThere are uses ofthis,For example, the following example:

varobj = {a:'tom',b:function(){Console.log(this.a);}};obj.b();//The output istom

In this casethispoints to the call to the function Object,Here isobj,Another example is the following example:

varobj = {a:'tom',b:function(){   console.log(this.a);},c: {c0:'rose',c1:function(){console.log(this.c0);}}};obj.c.c1();//Outputjack

FunctionWhen calledcontains multiple objects, although this function is the most When called by an outer object,thisonly points to its upper-level object

But in the opening example it is Why?

vara ='jack';varobj = {a:'tom',b:function(){   console.log(this.a);}};varc = obj.b;c();//Outputjack

Everyone should remember one sentencethispoints to the object that last called it,is thehere Although cis assigned the value,ofobj.b, the variablecis still hung on the globalwindowobject,so in the endthispoints to the globalwindowobject

2.Call the function directly

That is, directly use declarative or variable declaration functions,directly call the function globally

varname ='tom';vara=function(){varname ='jack';console.log(this.name);};console.log(a());//Outputtom

Theahere is in the globalwindowin the statement,When called, it is also equivalent towindow.a(), sothispoints to the globalwindowObject,Including this situation:

varname ='tom';vara=function(){varname ='jack';functionb(){console .log(this.name);}b();//Outputtomconsole.log(this.name);};console.log(a());//Outputtom

aandboutput bothtom,functionbWhen subsequently called in functiona, it still points to the globalwindowobject,Why is this?Everyone can remember one sentence,jsAs long as there is no object, the function is called directly,When the function is called, the pointer ofthiswill be pointed to the globalwindowobject

Like the previous example, when calling, obect.function(), the pointer of thiswill be pointed toobject,such as

varobj = {a:'tom',b:function(){    console.log(this.a);}};obj.b();//Outputtom

Like the opening example, it is easy to understand with this sentence,The call of functioncdoes not call the object, so it will be Point to the globalwindowobject

vara ='jack';varobj = {a:'tom',b:function(){Console.log(this.a);}};varc = obj.b;c( );//Outputjack

##3.

In the constructor Thethispoints to##There is no obvious distinction between the constructor and the ordinary function in Js

,When any ordinary function is used to create a type of object, it is called a constructor, or constructor. For a function to serve as a true constructor, it needs to meet the following conditions:1

, and create a new object inside the function (

this) properties are set, usually by adding properties and methods.

2

,The constructor can contain a return statement (not recommended), but the return value must bethis, or other non-object type values.

For example

:

functionPeople(name,age,sex){this.name= name;this.age= age;this.sex= sex;}varp =newPeople('tom',12,'Male');console.log(p.namep.sexp.age);//Outputtom12

thishere points to the currently created object

Of course there are also special cases for constructors,For example:

functionPeople(name,age,sex){this.name= name;this.age= age;this.sex= sex;return{};}varp =newPeople('tom',12,'Male');console.log(p.name);//Outputundefined

#It is not difficult to understand here that the constructor requires the return value to bethisor a non-object type,So thePeoplehere is not a constructor in the strict sense,is declared herepis actually just the return value of functionPeople,so the final output isundefined,If you change the return value here to a non-object type,the final result will be different

functionPeople(name,age,sex){this.name= name;this.age= age;this.sex= sex;return1;}varp =newPeople('tom',12,'Male');console.log(p.name);//Outputtom

ThePeoplehere is the constructor in the strict sense,sothisstill points to the currently created object

4.callorapplyCall function

CallandapplyThe usage of the function is almost the same,The first parameter is the object of the calling function,The following parameters They are all parameters of the function,It’s just thatcallThe parameter passing method of the function is to pass an unlimited number of parameters,That is,call([thisObject[,arg1 [,arg2 [,...,argn]]]])The following parameters correspond to the functions The parameters of the call,and the first parameter of theapplyfunction is the same ascall,The second parameter is the array type,apply([thisObj [,argArray] ])Each element of the array also Corresponding to the parameters of the function callrespectively,When usingcallorapplythe function is,thisin themethod will be redirected tocallorapplyThe first parameter of the function,For example:

vara =1;varb =2;varc = {a:3,b:4};functionadd(){console.log(this.athis.b)}add();//Output3add.apply(c);//Output7

When the firstaddis called, there is no direct call to the object, so it will is pointed to the globalwindowobject, so the output result is3,and the firstaddThefunction is called through theapplyfunction, so the pointer tothiswill be directed tocSo the final output result is7

Es6Extension:

The

thisof the arrow function inEs6points to the samethis## ases5#It’s different,Let’s mention it here:Because the arrow function is not boundthis, it will capture thethisvalue of the context in which it is located (i.e. where it is defined) as its ownthisvalue, So thecall() / apply() / bind()method just passes in parameters for the arrow function, and itsthis无 Impact. Considering thatthisis at the lexical level, rules related tothisin strict mode will be ignored.

1 .

Arrow functions in objects

vara = {name:'tom',b: {c: () => {    console.log(this);}},};a.b.c();//Output## Usingthisin the#window

object will be pointed to the globalwindowobject,So when you use an arrow function in an object, the point ofthiswill also be pointed to the globalwindowObject.2. Calling arrow functions in methods

vartest=function(){this.time=1;setTimeout(()=>{console.log(this.time);},100)};vart =newtest();//Output1

There is nothispointer in the arrow function,, so the pointer is only related to the context in which it was created.,Here is the call of the constructor, so#thisintestpoints to It istobject,sothisin the arrow function also points to the object

This article introduces this in Javascript. For more related content, please pay attention to the php Chinese website.

Related recommendations:

Detailed explanation on uploading word, txt, Excel, PPT and other files to the WeChat applet

WeChat applet download file, how to process it through back-end PHP

##Introducing 7 tips to improve MySQL performance

The above is the detailed content of Explanation of this in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!