The direction of this in js

  • 2021-07-01 06:17:32
  • OfStack

In js, the direction of this is definitely a difficult problem for beginners, but if you really understand it, there will be no problem. Let's talk about this.

In JS, the value of this depends on the invocation mode (invocation object), while there are four invocation modes in JS:

1. Function call pattern

When a function is not a property of an object, it is called as two functions, and the this in the function points to the global object (window in the case of large logarithms)


window.value=1;
function getValue(){
 console.log(this.value);
}
getValue();// Output 1 At this time this Point window

2. Method invocation pattern

When a function is a property of an object, we call it a method of the object, and when a method is called, this points to the object


var Obj={
  value:2,
  getValue:function(){
       console.log(this.value);// Output 2,this Point Obj
  }   
}

! ! ! In this pattern, the binding of this to the object occurs when the method is called

3. Constructor invocation pattern

The function called using new is called a constructor function, and this at this time points to the object that the constructor function instances


function main(val){
  this.value=val;
}
main.prototype.getValue=function(){
  console.log(this.value);
}

var fun=new main(3);
fun.getValue();
fun.value;// Output 3 , this Point main Instance object of fun

4. apply/call call mode and bind

The apply, call, bind methods let us set who the this in the caller points to


function showValue(){
  console.log(this.value);
}
var obj={
  value:4
}
showValue.call(obj)// Output 4 , this Points to obj Object 

bind method is added in ECMA5. The specific usage can be under google1. Here is a demonstration of the usage of this binding


function showValue(){
  console.log(this.value);
}
var obj={
  value:4
}
var showValue2=showValue.bind(obj);
showValue2()// Output 4 , this Points to obj Object 

bind has many usages, you can check it yourself


Related articles: