I want to do global event handling for reporting JavaScript errors. We have minified JS files in production so I'm attempting get it done with the help of sourcemap.
Unfortunately, uncaught errors (reported by the browser's top-level
error handler, window.onerror) do not currently include column numbers
in any current browser. The HTML5 Spec has been updated to require
this, so this may change in the near future.
Source : https://rollbar.com/docs/guides_sourcemaps/
So now I need to wrap backbone view events in try catch block. There should be generic way of extending Backbone.View. Probably somewhere at delegateEvents function.
Here is how finally I wrapped all jQuery event handlers in try-catch block.
// maintain a reference to the existing function
var oldOn = $.fn.on;
// ...before overwriting the jQuery extension point
$.fn.on = function(types, selector, data, fn, /*INTERNAL*/ one) {
// parameter correction for backward compatibility copied from `on` function of jQuery JavaScript Library v1.9.0
// Types can be a map of types/handlers
if (typeof types === "object") {
// ( types-Object, selector, data )
if (typeof selector !== "string") {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for (type in types) {
this.on(type, selector, data, types[type], one);
}
return this;
}
if (data == null && fn == null) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if (fn == null) {
if (typeof selector === "string") {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if (fn === false) {
fn = returnFalse;
} else if (!fn) {
return this;
}
// ENDS - parameter correction for backward compatibility copied from `on` function of jQuery JavaScript Library v1.9.0
if (fn) {
var origFn = fn;
var wrappedFn = function() {
try {
origFn.apply(this, arguments);
} catch (e) {
//handle the error here.
}
};
fn = wrappedFn;
}
return oldOn.apply(this, [types, selector, data, fn, /*INTERNAL*/ one]);
};
UPDATE:
There was a bug that jQuery-UI droppable divs were sticking to mouse pointer like glue ;) instead of getting dropped and it was traced to this code as culprit.
So please make sure you wrap this extension with condition if(!(arguments.length === 4 && arguments[1] === null)) {}
Like this.
// maintain a reference to the existing function
var oldOn = $.fn.on;
// ...before overwriting the jQuery extension point
$.fn.on = function(types, selector, data, fn, /*INTERNAL*/ one) {
// We can ignore .bind() calls - they are passed from jquery-ui or other outdated components
if(!(arguments.length === 4 && arguments[1] === null)) {
//rest of the above code here.
}
}
I've recently run across a situation in which I'd like to change Bootstrap's default behavior at a fundamental level. I'd like to add a custom method to the Modal class so that a custom method may be called like any other stock Modal method:
$('#my-modal').modal('myMethod', myParameter);
I have this working by adding a function to the Modal's constructor:
$.fn.modal.Constructor.prototype.myMethod = function (myParameter) {
...
}
However, the myParameter variable is not being passed. How do I access/pass myParameter to a custom Bootstrap method?
There is no way of you doing this as-is. The code Model uses to call a function does not take parameters into consideration;
$.fn.modal = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('modal')
, options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option]() // <-- here
else if (options.show) data.show()
})
}
Your best bet would be to add a method to $.fn, and then retrieve the Model instance via $(this).data('modal'), as that's where Bootstrap stores the instance;
$.fn.foo = function (param) {
return this.each(function () {
var model = $(this).data('modal');
// blah blah blah
});
}
I found a way to do this, although unfortunately it involves changes to the Bootstrap source. The piece of code that does the actual method calling is this:
$.fn.modal = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('modal')
, options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option]()
else if (options.show) data.show()
})
}
To change this, the 7th line (line 206 in the source code) should be modified to pass any additional parameters that were originally passed to the enclosing function. In addition, the original arguments must be given to each iteration of jQuery's .each() function. Here's the working code:
$.fn.modal = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('modal')
, options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option].apply($this.data('modal'), Array.prototype.slice.call(arguments, 1)); // pass the parameters on
else if (options.show) data.show()
}, arguments) // execute each iteration with the original parameters
}
I'm still experimenting to make sure this change doesn't create any undesirable side effects, but so far, everything works as expected. Any more elegant solutions would be welcome.
I'm trying to get:
document.createElement('div') //=> true
{tagName: 'foobar something'} //=> false
In my own scripts, I used to just use this since I never needed tagName as a property:
if (!object.tagName) throw ...;
So for the second object, I came up with the following as a quick solution -- which mostly works. ;)
The problem is, it depends on browsers enforcing read-only properties, which not all do.
function isDOM(obj) {
var tag = obj.tagName;
try {
obj.tagName = ''; // Read-only for DOM, should throw exception
obj.tagName = tag; // Restore for normal objects
return false;
} catch (e) {
return true;
}
}
Is there a good substitute?
This might be of interest:
function isElement(obj) {
try {
//Using W3 DOM2 (works for FF, Opera and Chrome)
return obj instanceof HTMLElement;
}
catch(e){
//Browsers not supporting W3 DOM2 don't have HTMLElement and
//an exception is thrown and we end up here. Testing some
//properties that all elements have (works on IE7)
return (typeof obj==="object") &&
(obj.nodeType===1) && (typeof obj.style === "object") &&
(typeof obj.ownerDocument ==="object");
}
}
It's part of the DOM, Level2.
Update 2: This is how I implemented it in my own library:
(the previous code didn't work in Chrome, because Node and HTMLElement are functions instead of the expected object. This code is tested in FF3, IE7, Chrome 1 and Opera 9).
//Returns true if it is a DOM node
function isNode(o){
return (
typeof Node === "object" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
);
}
//Returns true if it is a DOM element
function isElement(o){
return (
typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string"
);
}
The accepted answer is a bit complicated, and does not detect all types of HTML elements. For example, SVG elements are not supported. In contrast, this answer works for HTML as well as SVG, etc.
See it in action here: https://jsfiddle.net/eLuhbu6r/
function isElement(element) {
return element instanceof Element || element instanceof HTMLDocument;
}
Cherry on top: the above code is IE8 compatible.
No need for hacks, you can just ask if an element is an instance of the DOM Element:
const isDOM = el => el instanceof Element
All solutions above and below (my solution including) suffer from possibility of being incorrect, especially on IE — it is quite possible to (re)define some objects/methods/properties to mimic a DOM node rendering the test invalid.
So usually I use the duck-typing-style testing: I test specifically for things I use. For example, if I want to clone a node I test it like this:
if(typeof node == "object" && "nodeType" in node &&
node.nodeType === 1 && node.cloneNode){
// most probably this is a DOM node, we can clone it safely
clonedNode = node.cloneNode(false);
}
Basically it is a little sanity check + the direct test for a method (or a property) I am planning to use.
Incidentally the test above is a good test for DOM nodes on all browsers. But if you want to be on the safe side always check the presence of methods and properties and verify their types.
EDIT: IE uses ActiveX objects to represent nodes, so their properties do not behave as true JavaScript object, for example:
console.log(typeof node.cloneNode); // object
console.log(node.cloneNode instanceof Function); // false
while it should return "function" and true respectively. The only way to test methods is to see if the are defined.
A simple way to test if a variable is a DOM element (verbose, but more traditional syntax :-)
function isDomEntity(entity) {
if(typeof entity === 'object' && entity.nodeType !== undefined){
return true;
}
else{
return false;
}
}
Or as HTMLGuy suggested (short and clean syntax):
const isDomEntity = entity =>
typeof entity === 'object' && entity.nodeType !== undefined
You could try appending it to a real DOM node...
function isDom(obj)
{
var elm = document.createElement('div');
try
{
elm.appendChild(obj);
}
catch (e)
{
return false;
}
return true;
}
How about Lo-Dash's _.isElement?
$ npm install lodash.iselement
And in the code:
var isElement = require("lodash.iselement");
isElement(document.body);
This is from the lovely JavaScript library MooTools:
if (obj.nodeName){
switch (obj.nodeType){
case 1: return 'element';
case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
}
}
The using the root detection found here, we can determine whether e.g. alert is a member of the object's root, which is then likely to be a window:
function isInAnyDOM(o) {
return (o !== null) && !!(o.ownerDocument && (o.ownerDocument.defaultView || o.ownerDocument.parentWindow).alert); // true|false
}
To determine whether the object is the current window is even simpler:
function isInCurrentDOM(o) {
return (o !== null) && !!o.ownerDocument && (window === (o.ownerDocument.defaultView || o.ownerDocument.parentWindow)); // true|false
}
This seems to be less expensive than the try/catch solution in the opening thread.
Don P
old thread, but here's an updated possibility for ie8 and ff3.5 users:
function isHTMLElement(o) {
return (o.constructor.toString().search(/\object HTML.+Element/) > -1);
}
var IsPlainObject = function ( obj ) { return obj instanceof Object && ! ( obj instanceof Function || obj.toString( ) !== '[object Object]' || obj.constructor.name !== 'Object' ); },
IsDOMObject = function ( obj ) { return obj instanceof EventTarget; },
IsDOMElement = function ( obj ) { return obj instanceof Node; },
IsListObject = function ( obj ) { return obj instanceof Array || obj instanceof NodeList; },
// In fact I am more likely t use these inline, but sometimes it is good to have these shortcuts for setup code
I think prototyping is not a very good solution but maybe this is the fastest one:
Define this code block;
Element.prototype.isDomElement = true;
HTMLElement.prototype.isDomElement = true;
than check your objects isDomElement property:
if(a.isDomElement){}
I hope this helps.
This could be helpful: isDOM
//-----------------------------------
// Determines if the #obj parameter is a DOM element
function isDOM (obj) {
// DOM, Level2
if ("HTMLElement" in window) {
return (obj && obj instanceof HTMLElement);
}
// Older browsers
return !!(obj && typeof obj === "object" && obj.nodeType === 1 && obj.nodeName);
}
In the code above, we use the double negation operator to get the boolean value of the object passed as argument, this way we ensure that each expression evaluated in the conditional statement be boolean, taking advantage of the Short-Circuit Evaluation, thus the function returns true or false
According to mdn
Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements.
We can implement isElement by prototype. Here is my advice:
/**
* #description detect if obj is an element
* #param {*} obj
* #returns {Boolean}
* #example
* see below
*/
function isElement(obj) {
if (typeof obj !== 'object') {
return false
}
let prototypeStr, prototype
do {
prototype = Object.getPrototypeOf(obj)
// to work in iframe
prototypeStr = Object.prototype.toString.call(prototype)
// '[object Document]' is used to detect document
if (
prototypeStr === '[object Element]' ||
prototypeStr === '[object Document]'
) {
return true
}
obj = prototype
// null is the terminal of object
} while (prototype !== null)
return false
}
console.log(isElement(document)) // true
console.log(isElement(document.documentElement)) // true
console.log(isElement(document.body)) // true
console.log(isElement(document.getElementsByTagName('svg')[0])) // true or false, decided by whether there is svg element
console.log(isElement(document.getElementsByTagName('svg'))) // false
console.log(isElement(document.createDocumentFragment())) // false
I think that what you have to do is make a thorough check of some properties that will always be in a dom element, but their combination won't most likely be in another object, like so:
var isDom = function (inp) {
return inp && inp.tagName && inp.nodeName && inp.ownerDocument && inp.removeAttribute;
};
In Firefox, you can use the instanceof Node. That Node is defined in DOM1.
But that is not that easy in IE.
"instanceof ActiveXObject" only can tell that it is a native object.
"typeof document.body.appendChild=='object'" tell that it may be DOM object, but also can be something else have same function.
You can only ensure it is DOM element by using DOM function and catch if any exception. However, it may have side effect (e.g. change object internal state/performance/memory leak)
Perhaps this is an alternative? Tested in Opera 11, FireFox 6, Internet Explorer 8, Safari 5 and Google Chrome 16.
function isDOMNode(v) {
if ( v===null ) return false;
if ( typeof v!=='object' ) return false;
if ( !('nodeName' in v) ) return false;
var nn = v.nodeName;
try {
// DOM node property nodeName is readonly.
// Most browsers throws an error...
v.nodeName = 'is readonly?';
} catch (e) {
// ... indicating v is a DOM node ...
return true;
}
// ...but others silently ignore the attempt to set the nodeName.
if ( v.nodeName===nn ) return true;
// Property nodeName set (and reset) - v is not a DOM node.
v.nodeName = nn;
return false;
}
Function won't be fooled by e.g. this
isDOMNode( {'nodeName':'fake'} ); // returns false
You can see if the object or node in question returns a string type.
typeof (array).innerHTML === "string" => false
typeof (object).innerHTML === "string" => false
typeof (number).innerHTML === "string" => false
typeof (text).innerHTML === "string" => false
//any DOM element will test as true
typeof (HTML object).innerHTML === "string" => true
typeof (document.createElement('anything')).innerHTML === "string" => true
This is what I figured out:
var isHTMLElement = (function () {
if ("HTMLElement" in window) {
// Voilà. Quick and easy. And reliable.
return function (el) {return el instanceof HTMLElement;};
} else if ((document.createElement("a")).constructor) {
// We can access an element's constructor. So, this is not IE7
var ElementConstructors = {}, nodeName;
return function (el) {
return el && typeof el.nodeName === "string" &&
(el instanceof ((nodeName = el.nodeName.toLowerCase()) in ElementConstructors
? ElementConstructors[nodeName]
: (ElementConstructors[nodeName] = (document.createElement(nodeName)).constructor)))
}
} else {
// Not that reliable, but we don't seem to have another choice. Probably IE7
return function (el) {
return typeof el === "object" && el.nodeType === 1 && typeof el.nodeName === "string";
}
}
})();
To improve performance I created a self-invoking function that tests the browser's capabilities only once and assigns the appropriate function accordingly.
The first test should work in most modern browsers and was already discussed here. It just tests if the element is an instance of HTMLElement. Very straightforward.
The second one is the most interesting one. This is its core-functionality:
return el instanceof (document.createElement(el.nodeName)).constructor
It tests whether el is an instance of the construcor it pretends to be. To do that, we need access to an element's contructor. That's why we're testing this in the if-Statement. IE7 for example fails this, because (document.createElement("a")).constructor is undefined in IE7.
The problem with this approach is that document.createElement is really not the fastest function and could easily slow down your application if you're testing a lot of elements with it. To solve this, I decided to cache the constructors. The object ElementConstructors has nodeNames as keys with its corresponding constructors as values. If a constructor is already cached, it uses it from the cache, otherwise it creates the Element, caches its constructor for future access and then tests against it.
The third test is the unpleasant fallback. It tests whether el is an object, has a nodeType property set to 1 and a string as nodeName. This is not very reliable of course, yet the vast majority of users shouldn't even fall back so far.
This is the most reliable approach I came up with while still keeping performance as high as possible.
Test if obj inherits from Node.
if (obj instanceof Node){
// obj is a DOM Object
}
Node is a basic Interface from which HTMLElement and Text inherit.
For the ones using Angular:
angular.isElement
https://docs.angularjs.org/api/ng/function/angular.isElement
This will work for almost any browser. (No distinction between elements and nodes here)
function dom_element_check(element){
if (typeof element.nodeType !== 'undefined'){
return true;
}
return false;
}
differentiate a raw js object from a HTMLElement
function isDOM (x){
return /HTML/.test( {}.toString.call(x) );
}
use:
isDOM( {a:1} ) // false
isDOM( document.body ) // true
// OR
Object.defineProperty(Object.prototype, "is",
{
value: function (x) {
return {}.toString.call(this).indexOf(x) >= 0;
}
});
use:
o={}; o.is("HTML") // false
o=document.body; o.is("HTML") // true
here's a trick using jQuery
var obj = {};
var element = document.getElementById('myId'); // or simply $("#myId")
$(obj).html() == undefined // true
$(element).html() == undefined // false
so putting it in a function:
function isElement(obj){
return (typeOf obj === 'object' && !($(obj).html() == undefined));
}
Not to hammer on this or anything but for ES5-compliant browsers why not just:
function isDOM(e) {
return (/HTML(?:.*)Element/).test(Object.prototype.toString.call(e).slice(8, -1));
}
Won't work on TextNodes and not sure about Shadow DOM or DocumentFragments etc. but will work on almost all HTML tag elements.
A absolute right method, check target is a real html element
primary code:
(function (scope) {
if (!scope.window) {//May not run in window scope
return;
}
var HTMLElement = window.HTMLElement || window.Element|| function() {};
var tempDiv = document.createElement("div");
var isChildOf = function(target, parent) {
if (!target) {
return false;
}
if (parent == null) {
parent = document.body;
}
if (target === parent) {
return true;
}
var newParent = target.parentNode || target.parentElement;
if (!newParent) {
return false;
}
return isChildOf(newParent, parent);
}
/**
* The dom helper
*/
var Dom = {
/**
* Detect if target element is child element of parent
* #param {} target The target html node
* #param {} parent The the parent to check
* #returns {}
*/
IsChildOf: function (target, parent) {
return isChildOf(target, parent);
},
/**
* Detect target is html element
* #param {} target The target to check
* #returns {} True if target is html node
*/
IsHtmlElement: function (target) {
if (!X.Dom.IsHtmlNode(target)) {
return false;
}
return target.nodeType === 1;
},
/**
* Detect target is html node
* #param {} target The target to check
* #returns {} True if target is html node
*/
IsHtmlNode:function(target) {
if (target instanceof HTMLElement) {
return true;
}
if (target != null) {
if (isChildOf(target, document.documentElement)) {
return true;
}
try {
tempDiv.appendChild(target.cloneNode(false));
if (tempDiv.childNodes.length > 0) {
tempDiv.innerHTML = "";
return true;
}
} catch (e) {
}
}
return false;
}
};
X.Dom = Dom;
})(this);
Each DOMElement.constructor returns function HTML...Element() or [Object HTML...Element] so...
function isDOM(getElem){
if(getElem===null||typeof getElem==="undefined") return false;
var c = getElem.constructor.toString();
var html = c.search("HTML")!==-1;
var element = c.search("Element")!==-1;
return html&&element;
}
I have a special way to do this that has not yet been mentioned in the answers.
My solution is based on four tests. If the object passes all four, then it is an element:
The object is not null.
The object has a method called "appendChild".
The method "appendChild" was inherited from the Node class, and isn't just an imposter method (a user-created property with an identical name).
The object is of Node Type 1 (Element). Objects that inherit methods from the Node class are always Nodes, but not necessarily Elements.
Q: How do I check if a given property is inherited and isn't just an imposter?
A: A simple test to see if a method was truly inherited from Node is to first verify that the property has a type of "object" or "function". Next, convert the property to a string and check if the result contains the text "[Native Code]". If the result looks something like this:
function appendChild(){
[Native Code]
}
Then the method has been inherited from the Node object. See https://davidwalsh.name/detect-native-function
And finally, bringing all the tests together, the solution is:
function ObjectIsElement(obj) {
var IsElem = true;
if (obj == null) {
IsElem = false;
} else if (typeof(obj.appendChild) != "object" && typeof(obj.appendChild) != "function") {
//IE8 and below returns "object" when getting the type of a function, IE9+ returns "function"
IsElem = false;
} else if ((obj.appendChild + '').replace(/[\r\n\t\b\f\v\xC2\xA0\x00-\x1F\x7F-\x9F ]/ig, '').search(/\{\[NativeCode]}$/i) == -1) {
IsElem = false;
} else if (obj.nodeType != 1) {
IsElem = false;
}
return IsElem;
}
(element instanceof $ && element.get(0) instanceof Element) || element instanceof Element
This will check for even if it is a jQuery or JavaScript DOM element
The only way to guarentee you're checking an actual HTMLEement, and not just an object with the same properties as an HTML Element, is to determine if it inherits from Node, since its impossible to make a new Node() in JavaScript. (unless the native Node function is overwritten, but then you're out of luck). So:
function isHTML(obj) {
return obj instanceof Node;
}
console.log(
isHTML(test),
isHTML(ok),
isHTML(p),
isHTML(o),
isHTML({
constructor: {
name: "HTML"
}
}),
isHTML({
__proto__: {
__proto__: {
__proto__: {
__proto__: {
constructor: {
constructor: {
name: "Function"
},
name: "Node"
}
}
}
}
}
}),
)
<div id=test></div>
<blockquote id="ok"></blockquote>
<p id=p></p>
<br id=o>
<!--think of anything else you want--!>
I'm having trouble figuring out how I can take a string of an object name and check if that object actually exists.
What I'm trying to accomplish is have an array the defines the required objects for a particular JavaScript "module" to work, for instance:
var requiredImports = ['MyApp.Object1', 'MyApp.Object2'];
Then using requiredImports, I want to loop over them and check if the are defined. Without using the above array, I can do the following which is what I'm trying to accomplish:
if (MyApp.Object1 == undefined) {
alert('Missing MyApp.Object1');
}
But using the above, I'd have to hard code this for every module rather than making a generic method that I can just pass it an array of strings and have it effectively do the same check for me.
I tried doing this by just passing it the objects themselves such as:
var requiredImports = [MyApp.Object1, MyApp.Object2];
But that throws a JavaScript error when those objects do not exist, which is what I'm trying to catch.
var MyApp = {
Object1: {}
};
function exists(varName, scope) {
var parent = scope || window;
try {
varName.split('.').forEach(function (name) {
if (parent[name] === undefined) {
throw 'undefined';
}
parent = parent[name];
});
}
catch (ex) {
return false;
}
return true;
}
console.log(
exists('MyApp.Object1'), // true
exists('MyApp.Object2'), // false
exists('window'), // true
exists('document'), // true
exists('window.document') // true
);
// or
console.log(
['MyApp.Object1', 'MyApp.Object2', 'window', 'document', 'window.document'].filter(function (varName) {
return !exists(varName);
})
);
// => ["MyApp.Object2"]
Note: that forEach is ES5 and as such not implemented in some browsers. But if you'd go with this solution, there is a nice polyfill here.
You can check for definedness with
if ( typeof window['MyApp'] === 'undefined' ||
typeof window['MyApp']['Object1'] === 'undefined' )
{
alert('Missing MyApp.Object1');
}
and so on.
Assuming MyApp.Object1 is a global scope, window is the parent object and since that is the top level object, you don't need to prefix your global vars with it. So window.MyApp.Object1 is the same as MyApp.Object1 (again, assuming this is within global scope).
Also, in javascript, MyApp['Object1'] is the same as MyApp.Object1. So if we apply this principle to the main window object, you can check for window['MyApp'] or window['MyApp']['Object1'] and the key here is that you can replace 'MyApp' and 'Object1' with a variable.
Example:
/* check if a variable/object exists in the global scope) */
function checkIfExists(someVar) {
if (typeof(window[someVar]) == 'undefined')
return true;
return false;
}
var foo = 'bar';
alert(checkIfExists('foo'));
You can evaluate your custom expression in JavaScript. Consider the code below:
var MyApp = {
Object1: "foo",
Object2: "bar"
};
var IsExists = function(varName) {
return new Function('return typeof(' + varName + ') === "undefined" ? false : true;')();
};
USAGE
var requiredImports = ['MyApp.Object1', 'MyApp.Object2'];
for (var i = 0; i < requiredImports.length; i++)
{
alert(requiredImports[i] + ": " + IsExists(requiredImports[i]))
}
You only get error for first level (MyApp in your example). I assume you have only a few first-level requires, so check them manually by window[x] which does not throw:
var requiredTopLevel = ['MyApp'];
for (var i = 0; i < requiredTopLevel.length; ++i) {
if ("undefined" === typeof window[requiredTopLevel[i]]) {
// problem with requiredTopLevel[i]
}
}
and then, to check nested requires (if top-level is present) you can use the values without fear. For example this will work:
var requiredNested = { 'Object1':MyApp.Object1, 'Object2':Myapp.Object2 };
for (var name in requiredNested) {
if ("undefined" === typeof requiredNested[name]) {
// problem with name
}
}