I am writing a JavaScript utility which allows a user to detect if a particular object / function is available at runtime. Here is the source code, this works but it needs editing every time you want to test for another object:
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Template</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#TestObject').click(function() {
alert(typeof(HTMLCollection));
});
});
</script>
</head>
<body>
<input id="ObjectType" type="text" />
<input id="TestObject" type="button" value="Test" />
</body>
</html>
When the button is clicked, it displays an alert indicating “object” or “function” if the item exists, and “undefined” if it does not.
What I want is to have a textbox <input id="ObjectType" type="text" /> where I can type in the object to test, and then click the button to test it, which will eliminate the need to keep editing the document. Is this possible? Is there anything similar to reflection that I can use?
This is possible due to JavaScript object properties actually being associative key-value pairs, meaning that
obj.propertyis equivalent toobj['property'].Applying this to your problem, the following code would work:
This works because all “global” variables, are actually properties of the
windowobject.