Example of this in js

  • 2020-06-07 03:57:18
  • OfStack

This article gives an example of this usage in js. Share to everybody for everybody reference. The details are as follows:

1. Point to window

The global variable


alert(this) // return  [object Window]

Global function


function sayHello(){
  alert(this);
}
sayHello();

2. Points to the object (this points to window in the global, this to an object, this to window in the closure)


var user="the Window";
var box={
  user:'the box',
  getThis:function(){
    return this.user;
  },
  getThis2:function(){
    return function (){
      return this.user;
    }
  }
};
alert(this.user);//the Window
alert(box.getThis());//the box
alert(box.getThis2()());
//the Window  Because of the use of closures, the this Point to the window ) 
alert(box.getThis2().call(box));
//the box  Object masquerading as (here's this Point to the box Object) 

3. Use apply,call to change the this point of the function


function sum(num1, num2){
  return num1+num2;
}
function box(num1, num2){
  return sum.apply(this, [num1, num2]);
  //this  said window The scope of the  box Pretend to be sum To perform the 
}
console.log(box(10,10)); //20

4. new object


function Person(){
   console.log(this) // will  this  Point to the 1 A new empty object 
}
var p = new Person();

Hopefully, this article has helped you with your javascript programming.