Talking about Several Easy Handling ‘THIS’ Pointing Method in JS

I like to change the function in JS to perform the point of the context, also known as THIS pointing.

, for example, we can use array methods on class array objects:

  Const reduuce = array.Protype.Reduce; function suxction () {Return Reduce .call (Sum, Value) => {RETURN SUM + = Value;});} SUMARGS (1, 2, 3); // => 6  

It is difficult to grasp it on the other hand.

Let’s often find this THIS pointed to incorrect. The following teaches you how to simply bind THIS to the desired value.

Before starting, I need an auxiliary function Execute (FUNC), which only performs functions as parameters provided.

Function Execute (FUNC) {Return Func ();} Execute (function () {return 10}; // => 10
   
Now, continue to understand the essence of this error: method is separated.

1. Method separation problem

Assume that there is a class Person contains field firstname and lastname. In addition, it has a method getFullName (), which returns the full name of this person. As shown below:
Function Person (firstname, lastname) {this.firstname = fIrstName; this.lastname = lastname; this.getfullname = function () {this === agent; // => true return `$ {this.firstname} $ {this.lastname}`}}} const Agent = New Person (‘Front End’, ‘小智’); agent.getFullname (); // => ‘Front End Xiaozhi’

You can see the Person function as a constructor Call: New Person (‘front end’, ‘小智’). This is a newly created instance.

getFullName () Returns the full name of this person: ‘Front End Small. As expected, this THIS is equal to the Agent in the getFullName () method.
What happens if the auxiliary function executes the agent.getfullname method:
   Execute (agent.getfullname); // => 'undefined undefined' 

The result is incorrect: ‘undefined undefined’, which is the problem that this is incorrect.

Now in the getFullName () method, the value of this is a global object (Window in the browser environment). This is equal to Window, $ {window.firstname} $ {window.lastname} Execute result is ‘undefined undefined’.

This happens because when the execute (agent.getfullname)This method is separated from subjects. Basically occurring only a regular function call (not method call):

Execute (agent.getfullname); // => ‘undefined undefined’ // equivalent: Const getFullnameseparate; execute (getFullnameseparate); // => ‘undefined undefined’
This is the so-called method separated from its object, when the method Separated, then executed, this is not connected to the original object.
  In order to ensure that THIS inside the method points to the correct object, it must be done in the form of a property accessor: Agent.getFullName ()  
or Statically bind THIS to the included object (using an arrow function, .bind () method, etc.)

method separation problem, and thus causes THIS to not point to incorrect, generally below In the case of:

// `MethodHandler ()` is` This is the global object setTimeout Object.handlerMethod, 1000);
 When setting the event handler   
// React: `MethodHandler ) `THIS` is the global object

Click Me

  1. Connected to some useful partiesLaw, that is, if the method is separated from the object, how to point this to the desired object.
  2. 2. Close the context

Keeping this point to the simpler method of the class instance is to use an additional variable SELF:

Function Person (FirstName, Lastname) {this.firstname = firstname; this.lastname = lastname; const self = this; this.getfullname = function () {self === agent; // => True Return `$ {self.firstname} $ {self.lastname}`;}} const Agent = New Person (‘front end’, ‘小智’); agent.getfullname (); // => ‘front end Xiao Zhi’ Execute (agent.getfullname); // => ‘front-end Xiaozhi’
GetFullName () Statically close the SELF variable, effectively binding the THIS.
  Now, when the execute (agent.getfullname) is called, everything works fine because THIS always points to the correct value in the getFullName () method.  
3. Use the arrow function
Is there a way to static binding in the case of no additional variables? Yes, this is the role of arrow function.

Reconstructing the arrow function:
    
The arrow function is bound to the word method. Simply, it uses the value of the external function this from it.

It is recommended to use an arrow function in all situations that need to use an external function context.

4. Binding context
Now let’s further use the class in ES6 reconstructs Person.

Class Person {Constructor (firstname, lastname) {this.firstname = firstname; this.lastname = lastname;} getFullname () {Return `$ {this.firstname} $ {this.lastname} `;}} const Agent = New Person (‘front end’, ‘小智’); agent.getfullname (); // => ‘front end Xiaozhi’ Execute (agent.getfullname); // => ‘Undefined undefined’
  Unfortunately, even if new syntax is used, Execute (agent.getfullname) still returns "undefined undefined".  In the case of the class, the additional variable SELF or arrow function is used to repair the pointing of this. 
However, there is a trick involving a bind () method, it binds the context of the method into the constructor:

Class Person {Constructor (firstname , lastName) {this.firstName = firstName; this.lastName = lastName; this.getFullName = this.getFullName.bind (this);} getFullName () {return `$ {this.firstName} $ {this.lastName}`; }}}} const Agent = New Person (‘Front End’, ‘小智’); agent.getfullname (); // => ‘Front End Xiao Zhi’ Execute (Agent.GetFullName); // => ‘Front End Xiao Zhi’

THIS.GETFULLNAME = this.getFullname.bind (this) in the constructor is bound to class instances.
EXECUTE (Agent.GetFullname) returns ‘front end 智’ by expected.

5. Fat Arrow Method

Bind mode is a bit too long, we can use the fat arrow:

Class Person {Constructor (firstname, lastname) {this.firstname = firstname; this.lastname = LastName;} getfullname = () => {Return `$ {THIS. Firstname} $ {this.lastname} `;}} const Agent = New Person (‘front end’, ‘小智’); agent.getfullname (); // => ‘front end Xiao Zhi’ execute (agent.getfullname); // => ‘front-end Xiaozhi’
   Fat Arrow Method GetFullName = () => {...} Bind to class instance, even if the method is separated from it. 
This method is to bind the most effective and simple method of this in the class.
6. Summary

The method of separation with the object will generate this point to incorrect problems. Statically bind THIS, you can manually use an additional variable Self to save the correct context object. However, a better alternative is to use an arrow function, which is essentially to bind this in the lexical.

In the class, the BIND () method can be used to manually bind the class method in the constructor. Of course, if you don’t have to use Bind this lengthy manner, you can also use a simple and convenient fat arrow to represent a method. Original: https://github.com/valentinogagliardi/little-javascript-book/blob/v1.0.0/manuscript/chapter5.md

The above is this articleAll of the content, I hope to help everyone’s learning, I hope everyone will support Tumi Clouds.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment