For any JavaScript program, when the program starts running, the JavaScript interpreter initializes a global object for the program to use. The functions of global objects provided by this JavaScript itself include:
1. The global object has some commonly used property values. Such as undefined, Infinity and NaN.
2. The global object has some commonly used attribute objects. For example, Math, JSON and Number objects are all properties of the global object.
3. The global object provides some global functions for call. For example, isNaN(), isFinite(), parseInt() and eval(), etc.
4. The global object provides some global constructors, that is, global classes. For example, Date(), RegExp(), String(), Object(), and Array().
In addition to JS global objects, there is another global object for JavaScript programs running on the browser side: window. The window global object provides many attributes and methods related to the current window and page. In addition to these browser-related global properties and methods, the window object also encapsulates JS global objects and exposes the properties and interfaces of JS global objects to the outside; therefore, when performing browser-side JavaScript programming, you only need to care about the window global objects.
For this in a JavaScript program, if this does not belong to any function, then this refers to the JS global object; if it is a JS program running on the browser, then this refers to the window global object.
If this belongs to a function, then this refers to the object that calls the function. If function is just an ordinary function in this case, not a method of a certain class, then there are two possibilities for this reference:
1. Under the non-strict mode of the ECMAScript 3 standard and the ECMAScript 5 standard, this refers to the global object.
2. Under the strict mode of the ECMAScript 5 standard, this refers to undefined.
Based on this feature, you can use the following code to determine whether you are currently in strict mode:
The code copy is as follows:
var strict = (function(){return !this;}());
If a global variable is created in a JavaScript program, then this global variable becomes a property in the global object.
experiment
The code copy is as follows:
var a = this;
console.log(a);//window object
console.log(a.outerWidth);//access window object's attribute
console.log(a.isNaN);//access JS global object's attribute
x = "test";
console.log(ax);//access newly created global variable value