简体   繁体   中英

Who invok's a nested function in JS?

Just trying to clear some misconceptions...

function outer(){
    function inner(){

    }
}
  1. Does a function being a member of a particular object decides it's contextual this?

  2. Like, is it the reason that outer function is member of window object therefore the contextual this of outer function refers to window object?

  3. If yes then whos member is the inner function?

  4. Is inner member of outer function's object?

  5. And why the inner function's contextual this is referring to the window object?

  6. Is any function(global or nested) invoked without new operator will have contextual this referring to window object?

For an ordinary function (that is, not an arrow or member function), this is populated dynamically, at the call time. this depends on how the function is being called, not on where it's been declared.

this can be populated by 1) a property accessor ( object.func ) or 2) new as in new func() or 3) an indirection like call/apply . If the engine cannot populate this for a particular function call, it's set to the global/window in the sloppy mode and undefined in the strict mode. This applies to both global and inner functions.

Global functions being members of the global/window is an orthogonal concept and doesn't affect this in any way.

Inner functions, like local variables, are not members of any object.

Yes, the object to which a function belongs to determines the context of the this keyword within that function. If a function is a property of an object, the this keyword refers to that object. If a function is not a property of an object, then it is considered a global function and the this keyword refers to the window object.

An inner function is a property of its outer function and its this keyword is determined by how the inner function is invoked.

If a function is invoked without the new operator and it is not a property of an object, then the this keyword within the function refers to the window object. If it is invoked as a method of an object, the this keyword refers to the object.

in simple terms: The this keyword in JavaScript refers to the object that the function is associated with. If a function is a property of an object, this refers to that object. If a function is not associated with any object, then this refers to the global object (usually the window object in web browsers).

For example, if you have an object person with a method sayHello, this inside the sayHello method refers to the person object. If you have a standalone function, this refers to the global object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM