The usage of this in Javascript

  • 2020-03-30 03:56:55
  • OfStack

I used this in an interview the other day, and the interviewer told me that I had a little bit of a misunderstanding. I came back, read some books and blogs, did some tests, and found that my understanding was indeed wrong

1. Global variables

I think it's the most common one, but I call this in a function, and this is actually a global variable


var value="0"; function mei(){ 
 var value="1"; 
 console.log(this.value); //0  console.log(value);   //1 } 
mei();

Output 0 because this points to the global

2. Constructor

This is something that I'm familiar with, the constructor USES this, new, a new object and then this points to the new object


var value="window"; function mei(){ 
 this.value=1; 
 this.show=function(){ 
  console.log(this.value) 
 } 
} var m=new mei(); 
console.log(m.value);  //1 m.show();        //1

You can see that the output is 1 instead of window, so because of the constructor, this already points to a new object instead of a global variable

3. Call and apply

Borrow examples directly from my call and apply blogs


 var p="456"; 
 function f1(){ 
  this.p="123"; 
 } 
 function f2() { 
  console.log(this.p); 
 } 
 f2();       //456  f2.call(f1());  //123  f2.apply(f1());  //123

The first line of output 456 is easy to understand, this points to the global, and the next 123 is because after using call or apply, the this in f2 points to f1, while the p in f1 is 123

4. Function is called as a method on an object (where I made a mistake)

When I was asked to write an object, there were several methods. I defined a global variable in my mind, and then called it with this in the object's method. The interviewer asked me, "what is this?" I said it should be window, because I used this method less, thinking that only new or call would change the direction of this, he said wrong, let me go back and have a look, now I tried, I was really wrong, paste the code


var value="father"; function mei(){} 
mei.value="child"; 
mei.get=function(){console.log(this.value)}; 
mei.show=function(){console.log(value)}; 
mei.get();   //child mei.show();  //father

Since get is called as mei's method, this here points to mei.value and therefore outputs the child


Related articles: