This is used in javascript

I. The definition of this

This is an object that refers to different objects in different cases. When a function is called, an object is generated (how it is called, where it is called, arguments, etc.). Generally we use this to refer to global or local scopes instead of the current object in use. The main uses are: 1, to call 2 as an object method, and 3 as a constructor. Called after changing this direction with call or apply

2, This refers to

Call this without definition, this refers to the global scope. 3. When called by new, this always refers to the new object. 4. In the arrow function, this refers to the inheritance context in which the function is defined

The object

This object is easy to call, so if you call that object, this points to whoever it is

var person ={
name:'the 19'Age: '22'the print:function(a){
console.log (this)console.log (thisThe nmae + ', '+this.age)}} person.print();// This refers to the current object person
Copy the code

A function called directly

When called directly, this refers to the global window function

function print(a){
cnsole.log(this);
}
print();
// This points to the global scope
Copy the code

A function called by new

Function person (name, age) {this.name = name; function person (name, age) {this.name = name; this.age = age ; console.log (this); Var shijiu = new person (‘ 19 ‘, 22); // This refers to the new function of the new piece}

This in the arrow function

Note that there is no separate value for this in the arrow function; this in the arrow function is the same as the context in which the function is defined.

const person = {
a:() = > {
console.log(this); }}// The object calls the arrow function,
person.a();// This refers to window
Copy the code

This refers to change

There are three ways to change this: Call apply bind

call

The first argument in call is referred to by this, and the following arguments are passed to this,

function fn(x,y){
            console.log(this);  
        }
        var obj = {
            name:"pc"
        }
        fn(1.2);
        fn.call(obj,1.2);
Copy the code

apply

The first argument to apply points to this, followed by an array

function fn(x,y){
            console.log(this);  
        }
        var obj = {
            name:"pc"
        }
        fn(1.2);
        fn.apply(obj,[1.2]);
Copy the code

bind

Bind only changes the this pointer, and the argument needs to be passed manually

function fn(x,y){
            console.log(this);  
        }
        var obj = {
            name:"zs"
        }
        fn(1.2);
        fn.bind(obj,1.2) ();Copy the code

There are similarities and differences between the three methods

Common: All three can change the reference of this, and the first parameter passed is the object referred to by this, which takes the form of subsequent arguments. Difference: Call passes a single argument, while apply passes an array. Bind does not specify that single arguments and arrays can be used. Call and apply execute directly, while bind returns a function that is executed only when called.

The following is an extension:

Handwritten call Apply Bind source code

Write a call

Context is optional. If not, the default context is Window. Next create a fn property for the context and set the value to the function you want to call; Because call can pass multiple arguments as arguments to the calling function, you need to strip the arguments out; The function is then called and removed from the object.

// this is the function called
// Context is a parameter object
Function.prototype.myCall = function(context){ 
	// Determine whether the caller is a function
	if(typeof this! = ='function') {throw new TypeError('Error')}// The default value is window
 context = context || window 
 // Add the fn attribute, which sets the value to the function to be called
  context.fn = this
  Call [...arguments]
  const args = Array.from(arguments).slice(1)
   // Call the function
   constresult = context.fn(... args)// Delete the function
   delete context.fn 
   // Returns the execution result
   return result;
   }
  // A normal function
  function print(age){ 
  console.log(this.name+""+age);
   }
  // Custom objects
  var obj = { name:'pc' }
  // Call the function's call method
 print.myCall(obj,1.2.3)
Copy the code

Handwritten apply

So first context is optional, if you don’t pass it the default context is window and then you create a fn property for the context and set it to the function that you want to call because the apply pass is an array pass, so get the array, Strip it down to a sequential argument and make a function call and then call the function and delete the function on the object

// Write the apply method by hand
Function.prototype.myApply = function(context){ 
	// Determine whether the caller is a function
	if(typeof this! = ='function') {throw new TypeError('Error')}// No parameter The default value is
	window context = context || window 
	// Add the fn attribute, which sets the value to the function to be called
	context.fn = this // return execution result let result;
	// Check whether any arguments are passed in
	if(arguments[1]){ result = context.fn(... arguments[1])}else{
	result = context.fn() 
	}
	// Delete the function delete context.fn
	Return result;
}
// A normal function
function print(age,age2,age3){
	console.log(this.name+""+ age + ""+ age2+""+age3); 
}
// Custom objects
var obj = { 
	name:'pc' 
	}
	// Call the function's call method
print.myApply(obj,[1.2.3])
Copy the code

Write a bind

Determines whether the caller is a function. Intercepting parameters, note that there are two forms of parameter passing. Return a function, judging which way the function called external (new | direct call)

// Write a bind function
Function.prototype.myBind = function (context) { 
	// Determine whether the caller is a function
	if(typeof this! = ='function') {throw new TypeError('Error')}// Intercepts the passed arguments
		const args = Array.from(arguments).slice(1) 
		// _this points to the called function
		const _this = this; 
		// Return a function
		return function F(){ 
		// Since we return a function, we can new F(), so we need to determine
		 // In the case of new, this will not be changed in any way
		 if(this instanceof F){ 
		 	return new_this(... args,... arguments) }else{
		 	return_this.apply(context,args.concat(... arguments)) } } }// A normal function
		function print(){ 
		Bind [...arguments]
		console.log(this.name); 
		}
// Custom objects
var obj = { name:'pc'} / Call the function's call methodlet F = print.myBind(obj,1.2.3); 
// Return the object
let obj1 = new F(); 
console.log(obj1);
Copy the code