4

i have a little code snippet below

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

when the foo.bar function is executed, this refers to the window scope which of course knows nothing about baz so i have defined baz=1 in window. but the program still not working and returning undefined. why it is returning undefined while baz have defined in window and i am executing foo.bar from window

2
  • adding a blank line before your code would make it display correctly. Commented Mar 7, 2014 at 6:35
  • If you do bar: function () { console.log(this); return this.baz; } you can see that this refers to its parent, which is arguments. Commented Mar 7, 2014 at 6:45

3 Answers 3

7

When you execute the function like arguments[0](), then this is referring to the arguments object, which doesn't have the property baz, so it will still be undefined.

You could bind this to a certain object by:

arguments[0].call(foo) or arguments[0].apply(foo).

Sign up to request clarification or add additional context in comments.

Comments

0

"this" becomes scoped the bar function. If you change it to return foo.baz, it'll work

Comments

-1

foo.baz will work , but not this.baz. try reading the scopes in javascript

1 Comment

Because “try reading the scopes in javascript” doesn’t make sense, and this doesn’t answer the actual question of “why”.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.