Home > Web Front-end > JS Tutorial > 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
Release: 2020-06-17 16:36:17
forward
2373 people have browsed it

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);
})();
Copy after login

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!

Related labels:
source:webhek.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template