Home  >  Article  >  Web Front-end  >  Detailed explanation of methods to obtain various global object variables in JavaScript

Detailed explanation of methods to obtain various global object variables in JavaScript

coldplay.xixi
coldplay.xixiforward
2020-06-17 16:36:172334browse

Detailed explanation of methods to obtain various global object variables in JavaScript

Global variables have always been considered a bad programming method in programming languages. But the reality is that many well-known projects use global variables extensively. For example, MooTools puts a large number of objects into the global space, such as Browser objects and $$, etc. . The most famous jQuery also uses global variables. Therefore, the theory that "global variables are bad" is actually in a very ridiculous state.

It is a bad programming habit to expose global variables and allow users to modify them arbitrarily (unless it is specifically designed), which will make the program difficult to maintain. So, how do we know what global variables are in the existing global variable space? In fact, the method is very simple:

// UPDATE:  This method is too naive
// Returns an array of window property names
//keys(window);

// Inject an iframe and compare its `contentWindow` properties to the global window properties
(function() {
	var iframe = document.createElement('iframe');
	iframe.onload = function() {
		var iframeKeys = Object.keys(iframe.contentWindow);
		Object.keys(window).forEach(function(key) {
			if(!(key in iframeKeys)) {
				console.log(key);
			}
		});
	};
	iframe.src = 'about:blank';
	document.body.appendChild(iframe);
})();

We can do a test using the above code. You can directly press the function key F12 to open the console, enter the above code, and watch the output results. You will find that some objects, such as window, document, top, and location are built-in to JavaScript, while many others Objects are generated by third-party JavaScript code.

Recommended tutorial: "javascript basic tutorial"

The above is the detailed content of Detailed explanation of methods to obtain various global object variables in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:webhek.com. If there is any infringement, please contact admin@php.cn delete