Tuesday, December 23rd, 2008
Thomas Fuchs comes back with some JavaScript tips
<>p>Thomas has been busy working on freckle, but has jumped back onto his blog again to give us some short tips:Preventing console.log breakage
We have all been there. After a serious Firebug session, you forget to take out the console statements. Or, maybe you like to keep them in for the future. To be sure, you can redefine some no-ops:
-
-
f(window['console'] === undefined)
-
window.console = { log: Prototype.emptyFunction };
-
To not rely on Prototype, you can simply log: function() {}.
Kangax then shared his approach:
-
-
(function(__global){
-
if (!__global.console || (__global.console && !__global.console.log)) {
-
__global.console = {
-
log: (__global.opera && __global.opera.postError)
-
? __global.opera.postError
-
: function(){ }
-
}
-
}
-
})(this);
-
In this tip, Thomas talks about how he likes to use a little curry to reuse the same code in different ways.
For example, taking a generic page turner:
-
-
// pages are numbered from 1 to 10
-
var currentPage = 1, pageCount = 10;
-
-
function turnPage(dir){
-
currentPage += dir || 0;
-
-
currentPage =
-
(currentPage == 0) ? pageCount :
-
(currentPage == pageCount+1) ? 1 : currentPage;
-
-
// here we would do whatever is necessary to render
-
}
-
and currying some helpers:
-
-
var nextPage = turnPage.curry(1),
-
previousPage = turnPage.curry(-1);
-
Although the examples are using Prototype, other libraries have the equivalent curry power.
Related Content:











Funny, I noticed this problem the other day and came up with a similar solution:
if(!console) conole = {log: function(){return false}}
SnoreFest2008 RoundUp Extreme++!!!
if i wanted javascript tips i’d go to javascript.about.com.
I avoid console.log(), typing that is cumbersome in the middle of a frenetic debugging session! Instead I use a log() facade.
function log() { if (console) console.log.apply(console, arguments); }
See http://jaybyjayfresh.com/2008/11/10/consolelog-in-safari-doesnt-apply-bad-safari/