Niro* by cho45

#19 console.log in demo code

Codes in JSDeferred Cookbook is evaluated in browser as is. But I want output of console.log to show in general. So I had to override console.log and do it with following solution:

Codes are all string so there are two way to evaluate it as JS: eval() or new Function(code)(). In this case, I use latter because I want to override console.log.

var code = ...;
new Function('console', code)({
  log : function (arg) {

I created a dummy console object which has log function and passed it into functioned demo code with arguments named console. And then, all of console.log in code are belong to us.

This way has very high advantage for asynchronous code. If I use the way overriding original console.log and write back after doing, I must handling all asynchronous event.

blog comments powered by Disqus