Home > Web Front-end > JS Tutorial > Explanation of this in Javascript

Explanation of this in Javascript

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

The

this in Javascript points to

beginnerjavascript Everyone will have a lot of confusion about js#this, such as the following example:

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

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

The common this points in js are divided into 4kind:

1.

this in the object points to

What is this in an object, That is, the properties of the object are function, and function There are uses of this, For example, the following example:

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

In this case this points to the call to the function Object , Here is obj, Another example is the following example:

var obj = {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, this only points to its upper-level object

But in the opening example it is Why?

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

Everyone should remember one sentence this points to the object that last called it , is the here Although c is assigned the value , of obj.b, the variable c is still hung on the global window object,so in the endthis points to the global window object

2. Call the function directly

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

var name = 'tom';var a = function(){var name = 'jack';console.log(this.name);};console.log(a());//Output tom

The a here is in the global window in the statement , When called, it is also equivalent to window.a(), so this points to the global windowObject,Including this situation:

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

a and b output both tom, functionb When subsequently called in function a, it still points to the global window object, 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 of this will be pointed to the global window object

Like the previous example, when calling , obect.function(), the pointer of this will be pointed to object, such as

var obj = {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 functionc does not call the object, so it will be Point to the global window object

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

##3.

In the constructor The this points 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 be this, or other non-object type values.

For example

:

function People(name, age, sex){this.name = name; this.age = age;this.sex= sex;} var p = new People('tom',12,'Male');console.log(p.name p.sex p.age); //Output tom12

this here points to the currently created object

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

function People(name, age, sex){this.name = name; this.age = age;this.sex= sex;return {};}var p = new People('tom',12, 'Male');console.log(p.name);//Outputundefined

#It is not difficult to understand here that the constructor requires the return value to be this or a non-object type , So the People here is not a constructor in the strict sense , is declared herep is actually just the return value of function People, so the final output is undefined, If you change the return value here to a non-object type, the final result will be different

function People(name, age, sex){this.name = name; this.age = age;this.sex= sex;return 1;}var p = new People('tom',12,'Male');console.log(p.name);//Output tom

The People here is the constructor in the strict sense, so this still points to the currently created object

4. call or applyCall function

Call and applyThe 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 the apply function is the same as call, The second parameter is the array type, apply([thisObj [,argArray] ])Each element of the array also Corresponding to the parameters of the function call respectively, When using call or apply the function is , this in the method will be redirected to call or applyThe first parameter of the function, For example:

var a = 1;var b = 2;var c = {a: 3,b: 4};function add(){ console.log (this.a this .b)}add();//Output 3add.apply(c); //Output7

When the first add is called, there is no direct call to the object, so it will is pointed to the global window object, so the output result is 3, and the first add The function is called through the apply function, so the pointer to this will be directed to c So the final output result is7

Es6Extension:

The

this of the arrow function in Es6 points to the same this## as es5 #It’s different, Let’s mention it here: Because the arrow function is not boundthis , it will capture the this value of the context in which it is located (i.e. where it is defined) as its own this value, So the call() / apply() / bind() method just passes in parameters for the arrow function, and its this 无 Impact. Considering that this is at the lexical level, rules related to this in strict mode will be ignored.

1 .

Arrow functions in objects

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

object will be pointed to the global window object , So when you use an arrow function in an object, the point of this will also be pointed to the global window Object.2. Calling arrow functions in methods

var test = function(){this.time = 1; setTimeout(()=>{           console.log(this.time);}, 100)};var t = new test();//Output1

There is no this pointer 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 #this in test points to It is t object , so this in 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template