Just trying to clear some misconceptions...
function outer(){
function inner(){
}
}
Does a function being a member of a particular object decides it's contextual this ?
Like, is it the reason that outer function is member of window object therefore the contextual this of outer function refers to window object ?
If yes then whos member is the inner function ?
Is inner member of outer function's object ?
And why the inner function's contextual this is referring to the window object ?
Is any function(global or nested) invoked without new operator will have contextual this referring to window object ?
CodePudding user response:
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.
CodePudding user response:
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.