Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Puzzle - One Liner

Can you solve this without throwing an error? The answer is a one-liner. This is from a dead job posting, the answer was requested in the response. I thought it was a clever way to weed out respondents, but I can't seem to answer it without also getting an error.

The obvious solution:

f.moo(alert(f.foo));

But that throws TypeError: callback is undefined { message="callback is undefined", more...}

var f = (function(){
  return {
    foo : "bar",
    moo : function(callback){
      callback.call(this)
    }
  }
})();
//alert "bar" by foo
like image 941
Bonnie V. Avatar asked Sep 10 '26 19:09

Bonnie V.


1 Answers

You have to pass f.moo a function. You're calling alert and passing the result of alert( which is nothing) instead.

f.moo(function() { alert(this.foo); });
like image 125
VoteyDisciple Avatar answered Sep 12 '26 07:09

VoteyDisciple