1

If I am creating a function:

function one() {
    console.log(this)
}

, I understand this is the window object.

If I make this function and run one, why is this still the window object?

function one() {
   function two() {
       console.log(this)
   }
   return two()
}

wouldn't this now be relative to inside of one() ?

  • `this` will be referring to `window` unless you did `return new two();` in which case it would refer to `two()`. - Edit: Meant `window` and I thought you were making a `new one()` already. – hewiefreeman Jan 11 '21 at 01:24
  • Does this answer your question? [JavaScript this refers to window instead of object inside function](https://stackoverflow.com/questions/15831509/javascript-this-refers-to-window-instead-of-object-inside-function) – Canopus Jan 11 '21 at 01:29
  • 1
    A function's *this* is set when the function body is evaluated immediately after the call and before any part of it is executed. The value it is set to depends on how the function is called, the type of code (strict vs non strict) and the type of function (e.g. arrow functions adopt the *this* of their enclosing execution context). In plain functions, if *this* isn't set by the call, it defaults to the global (window in a browser) object or in strict mode will be undefined. – RobG Jan 11 '21 at 01:35
  • @hewiefreeman—I think you should just delete the comment. The first phrase is correct, but the OP already knows that. The rest is incorrect. If the return statement is `return new two()`, then in the *console.log* statement *this* will reference the new object created by calling *two* as a constructor, it will not reference *two* or the global object (*window* in a browser). – RobG Jan 11 '21 at 02:36
  • @RobG It seemed to me OP was trying to make a pseudo class, hence the inner function. The original intent is not clear either, so I see no reason to take it down. – hewiefreeman Jan 11 '21 at 20:22

0 Answers0