-12

Can Some one explain why highlighted section is coming as undefined**strong text**

Can some one explain this behavior

Arijit Sil
  • 29
  • 4

1 Answers1

0

This is due to the behavior of the "this" keyword on the different contexts where it's been used.

So here is the complete reference for this keyword

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

var foo = {  
    bar : function(){ 
            console.log(this); // For your reference
            return this.baz;  
          },
    baz: 1
};

(function(v){
    console.log(typeof arguments[0]()); // In this context "this" keyword refers to the current function "bar" and not the parent foo object, As the current function doesn't contain baz it returns undefined
    console.log(typeof foo.bar());  // In this context "this" keyword refers to its parent "foo" Object so this.baz will be refer to foo.baz and typeof 1 is a number
    console.log(typeof v()); // Here "this" keyword refers to the window object hence this.baz will refer to window.baz which is undefined
    return typeof arguments[0]();
})(foo.bar);
Community
  • 1
  • 1