Problem:
IE6 throws runtime errors on an error-free JavaScript file generated on the backend using JSP, PHP, ...etc.
Solution:
These runtime errors are due to IE6's inability to parse the file properly. Define the content-type of the document and set it to text/javascript. This will properly format the document and will remove any runtime errors thrown in IE6.
Wednesday, May 28, 2008
Check for extended properties inside for..in loops
Problem:
Running a for..in loop on an object returns all enumerated properties of that object, including any methods/properties added using the prototype property. In the age of ubiquitous JavaScript libraries such as Prototype that does extend built-in objects, not accounting for those extended properties could break your code.
Solution:
it's essential to check for those extended methods and properties whenever the for..in loop is used. This is done by using the hasOwnProperty() Object method.
Running a for..in loop on an object returns all enumerated properties of that object, including any methods/properties added using the prototype property. In the age of ubiquitous JavaScript libraries such as Prototype that does extend built-in objects, not accounting for those extended properties could break your code.
Solution:
it's essential to check for those extended methods and properties whenever the for..in loop is used. This is done by using the hasOwnProperty() Object method.
for (var elem in FunObject) {
if (FunObject.hasOwnProperty()) {
// proceed with code
}
}
Labels:
built-in objects,
defensive programming,
javascript,
loops,
prototype
Check availibility of user-defined objects before you using them
Problem:
Oftentimes, programmers take the existence of user-defined variables, properties and objects for granted, which in turn results into unstable code that works when those objects exist and fails when they don't.
Solution:
Always check the existence of the following objects before manipulating them:
Oftentimes, programmers take the existence of user-defined variables, properties and objects for granted, which in turn results into unstable code that works when those objects exist and fails when they don't.
Solution:
Always check the existence of the following objects before manipulating them:
- DOM objects
var elem_to_test = document.getElementById('ad-unit');
if (elem_to_test) {
// proceed with code
} - Global JavaScript variable/object
if (typeof YAHOO != 'undefined') {
// proceed with code
}
OR
if (window.YAHOO) {
// proceed with code
} - Object property
if (window.obj && obj.property) {
// proceed with code
}
Subscribe to:
Posts (Atom)