HTML and CSS Reference
In-Depth Information
Listing 10.9 Defensively defining strftime
(function () {
if (Date.prototype.strftime ||
!String.prototype.replace) {
return;
}
var str = "%a %b";
var regexp = /%([a-zA-Z])/g;
var replaced = str.replace(regexp, function (m, c) {
return "[" + m +""+c+"]";
});
if (replaced != "[%a a] [%b b]") {
return;
}
Date.prototype.strftime = function () {
/* ... */
};
Date.formats={/*...*/};
}());
This way the Date.prototype.strftime method will only be provided
in browsers that can support it correctly. Thus, a feature test should be employed
before using it, as seen in Listing 10.10.
Listing 10.10 Using strftime
if (typeof Date.prototype.strftime == "function") {
// Date.prototype.strftime can be relied upon
}
// ... or
if (typeof someDate.strftime == "function") {
/* ... */
}
Because strftime is a user-defined method, the type check should be safe.
If compatibility with very old browsers was important, the strftime method
could be implemented using match and a loop rather than relying on the replace
method accepting a function argument. However, the point here is not necessarily
gaining the widest possible support, i.e., supporting Internet Explorer 5.0 probably
 
Search WWH ::




Custom Search