Home  >  Article  >  Web Front-end  >  JS useful information sharing--this points to the problem

JS useful information sharing--this points to the problem

hzc
hzcforward
2020-06-18 09:22:462047browse

Usually using this is a bit confusing, so I will write a summary.

Before there was no arrow function, we said that this was the environment object where the function was running, but in the arrow function this was the object where it was defined. Let’s talk about what everyone knows first: function running The environment object where it is located at the time.

1. As a function call, this points to the global object

#2. As a method call on an object, the object is the calling context, and this points to the object. .

#3. As a constructor call, the constructor attempts to initialize the newly created object and uses this object as its calling context, with this pointing to the newly created object.

4. Indirect call through the call/apply method of the function. The first parameter of the call/apply method is the calling context. In the function body, get the access to it through this Quote.

In the arrow function, the this object is the scope in which it is defined. That is to say, the arrow function itself does not have this, and the internal this is the outer code. this in block scope.

5, independent function

This arrow function is defined in the global environment, that is, this points to window

6、Object methods

As shown above, foo is defined globally, so this points to window, so how to make this point to obj ?

According to the previous article, when a function is called as a method of an object, this points to the object and can be rewritten like this:

# #func is defined when foo is called. The scope of foo at this time is obj, so this points to obj

7

and constructor . Since the arrow function does not have this, it cannot be used as a constructor. function, otherwise an error will be reported

##8

,

bind/call

as above :

func is defined globally, so it prints 0. Same as the object method, we can rewrite it as follows to print out 1

Recommended tutorial: "

JS Tutorial


The above is the detailed content of JS useful information sharing--this points to the problem. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete