0

Possible Duplicate:
Chrome doesn’t recognize console.log when it’s called log

Can anyone tell me why this doesn't work when I set the method to console.log?

var met = "console.log";
var msg = "HELLO WORLD";
var n = met.split(".");
var f = this;
$.each(n, function(k, v){
    f = f[v];
});
f(msg);

this seems to work when I tried using alert

Community
  • 1
  • 1
Farez Ramilo
  • 57
  • 1
  • 7

2 Answers2

1

It's because the log function of console gets assigned to the f variable, but when executed it has no reference to the console scope anymore. Javascript scoping can get tricky when dealing with callbacks or passing functions around.

As far as @Murali's comment that it works, some browsers implement the console.log method differently than others.

As an experiment, try running this code and see if it works:

var met = "console.log";
var msg = "HELLO WORLD";
var n = met.split(".");
n[1].call(n[0], msg);

Using the .call method lets you execute a function and declare its' scope. If that works for you, it should be easy to refactor your loop scenario.

Stephen
  • 18,827
  • 9
  • 60
  • 98
0

Solved it.

var met = "console.log";
var msg = "HELLO WORLD";
var n = met.split(".");
var tail = n.pop();
var f = this;
$.each(n, function(k, v){
    f = f[v];
});
var func = function(){ f[tail].apply(f, arguments); }
func(msg);

Tested this working on Chrome, Firefox, Opera and Safari. Doesn't seem to work on IE9.

I got the ideas from @muistooshort on Link and also from @jasonbunting on Link

Community
  • 1
  • 1
Farez Ramilo
  • 57
  • 1
  • 7