This article mainly introduces the usage of this in js. The example analyzes how this points to windows, points to objects, and related skills for changing this points, if you need this, refer to the example in this article to describe how to use this in js. Share it with you for your reference. The details are as follows:
1. Point to window
Global Variables
Alert (this) // Returns [object Window]
Global Functions
function sayHello(){ alert(this);}sayHello();
2. Point to this object (in the global context, this points to window, this points to this object in an object, and this points to window in the closure)
Var user = "the Window"; var box = {user: 'The box', getThis: function () {return this. user;}, getThis2: function () {return this. user ;}}; alert (this. user); // the role walert (box. getThis (); // the boxalert (box. getThis2 (); // the Window (because the closure is used, this points to the window) alert (box. getThis2 (). call (box); // impersonate the box object (here this points to the box object)
3. Use apply and call to change this point of the function.
Function sum (num1, num2) {return num1 + num2;} function box (num1, num2) {return sum. apply (this, [num1, num2]); // this indicates that the window scope box impersonates sum for execution} console. log (box (10, 10); // 20
4. new Object
Function Person () {console. log (this) // point this to a new empty object} var p = new Person ();
I hope this article will help you design javascript programs.