0

when we call foo, it return a function which is inside foo function so if it is invoking inside the foo and fox function will return 'this' in the context of foo right? so shouldn't

  function foo(){

    function fox(){
            return this.fox; 
    }
   
    return fox();
    
}

foo(); //undefined

it return the function instead of undefined.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
Nish
  • 353
  • 3
  • 9
  • 1
    If you call `console.log(this)` insde `fox` function, you will see it outputs the Window object rather than a new "foo" object. – E. Zacarias Jul 20 '20 at 14:25
  • "*if it is invoking inside the foo and fox function will return 'this' in the context of foo right?*" - no. You're not calling `fox` as a method (like `obj.fox()`), so the `this` argument is `undefined` (and becomes the global object in sloppy mode). Also, there is no object in your code that has a `.fox` property, so `this.fox` will *always* be undefined no matter how `fox` is called. – Bergi Jul 20 '20 at 14:45

1 Answers1

0

You are calling foo() as a funtion. this binding occurs when you create an instance.

function foo(){

    function fox(){
       console.log(this);
    }
   
    return new fox();   // Again, an instance provides this binding
}

// When you create an instance using a constructor function
// this is bound to the instance
let inst = new foo();  // {}
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • so i have read in mdn [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions] that 'regular' functions create their own 'this' so we use arrow functions to if dont want and lexcially bind their enclosing scope – Nish Jul 20 '20 at 14:27
  • I don't know exactly what you read, but `this` binding occurs when a function is used as a constructor function (called with `new`). As you saw from your question, when you call a function as a normal function, you don't get `this` binding. – Scott Marcus Jul 20 '20 at 14:29
  • 1
    @NishilK. That article just says that an Arrow function is syntactically similar to a regular function. Both arrow functions and regular functions don't have their own `this` binding. – Scott Marcus Jul 20 '20 at 14:32
  • @NishilK. This may help understanding how `this` binding works; https://stackoverflow.com/questions/41385835/invocation-context-and-execution-context-in-javascript-are-we-talking-of-th/41386097#41386097 – Scott Marcus Jul 20 '20 at 14:33
  • Uh, calling `foo` with `new` won't make the `fox()` call have a different `this` context. – Bergi Jul 20 '20 at 14:42
  • Thanks, but I don't think this is what the OP wanted to do. Also, a constructor function like `foo` (that is called with `new`) should never return an object – Bergi Jul 20 '20 at 14:51