1

Possible Duplicate:
Function Arguments Passing and Return

I need a little help with this

 var foo = {
     bar: function () {
         return this.baz;
     },
     baz: 1
 };
 (function () {
     return typeof arguments[0]();
 })(foo.bar);

This snippet when executed returns 'undefined' Can someone please explain why is this so ?

6
  • 1
    Hmmmm, I have seen this exact snippet before on SO... Commented Jul 4, 2012 at 8:41
  • 2
    @leppie with google I found this stackoverflow.com/q/8587730/995876 :P How sad that the accepted answer there is incorrect :X Commented Jul 4, 2012 at 8:43
  • @Esailija: That's not even the one I recall! It was a week or 2 ago. Commented Jul 4, 2012 at 8:45
  • 2
    @Esailija - Good find! Completely identical. This question should be closed, even if the accepted answer in the duplicate is incorrect. Commented Jul 4, 2012 at 8:47
  • 2
    @JamesAllardice the code in the questions is actually from perfection kills quiz, question 6 Commented Jul 4, 2012 at 8:59

1 Answer 1

0

You need to use the right scope for the call. Explicitly setting foo as the scope gives the expected result.

var foo = {
    bar: function () {
        return this.baz;
    },
    baz: 1
};
(function () {
    return arguments[0].call(foo);
})(foo.bar);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.