This example describes the usage of this in js. Share it for your reference. The details are as follows:
1. Point to window
Global variables
alert(this) //Return [object Window]
Global functions
function sayHello(){ alert(this); } sayHello();
2. Point to the object (in the global world this points to window, in a certain object this points to the object, in the closure this point to window)
var user="the Window"; var box={ user:'the box', getThis:function(){ return ; }, getThis2:function(){ return function (){ return ; } } }; alert();//the Window alert(());//the box alert(box.getThis2()()); //the Window (because of using closures, this point to window here)alert(box.getThis2().call(box)); //the box Object impersonation(HerethisPoint toboxObject)
3. Use apply, call to change the function's this pointer
function sum(num1, num2){ return num1+num2; } function box(num1, num2){ return (this, [num1, num2]); //this indicates the scope of window. The box impersonates sum to execute} (box(10,10)); //20
4. new object
function Person(){ (this) //Point this to a newly created empty object} var p = new Person();
I hope this article will be helpful to everyone's JavaScript programming.