js commonplace this points to the problem

        The direction of this in js must be a difficult problem for novices, but if you really understand it, there is no problem. Let's talk about this below.

In JS, the value of this depends on the calling mode (calling object), and there are 4 calling modes in JS:

1. Function call mode

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

  

window.dragon=1;
function getDragon(){
 console.log(this.dragon);
}
getDragon();//输出1,此时的this指向window

2. Method call mode

     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.

   In this mode, the binding of this object occurs when the method is called

var obj={
  dragon:2,
  getDragon:function(){
       console.log(this.dragon);//输出2,this指向Obj
  }   
}
obj.getDragon();

3. Constructor call mode

The function called by new is called a constructor function, and at this time, the point of this is the object that is instantiated by the constructor function.

function main(val){
  this.dragon=val;
}
main.prototype.getDragon=function(){
  console.log(this.dragon);
}
 
var fun=new main(3);
fun.getDragon();
fun.dragon;//输出3,this指向main的实例对象fun

4.apply/call calling mode and bind

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

function showDragon(){
  console.log(this.dragon);
}
var obj={
  dragon:4
}
showDragon.call(obj)//输出4,this指向了obj对象

The bind method in ES5 can be googled for specific usage. Here is a demonstration of the usage of this binding:

function showDragon(){
  console.log(this.dragon);
}
var obj={
  dragon:4
}
var showDragon2=showDragon.bind(obj);
showDragon2()//输出4,this指向了obj对象

There are many uses of bind, you can check it yourself

The point of this in the above cliché js is all the content shared by the editor. If there are any deficiencies, you can criticize and correct them. .

Guess you like

Origin blog.csdn.net/qq_35404844/article/details/129919860