javascriptfunctionthisexecutioncontext

Does a JavaScript-function can be seen as an execution context respectively as this?


In the lower example, why does the function outer which is assigned as method to the object-property with the identifier meth does not have an execution context which would be the this in the inner-function?

Since the function outer assigned to meth seems to automatically get the this-keyword set to the surrounding object as execution context, you could assume, that the function inner is getting handled the same way, or is it because a surrounding function can not be seen as an execution context, therefore JavaScript does not know for the function inner which execution context it is in, so it assumes the default, which is then window?

var foo = {
    meth: function outer() {
        console.log(this);
        // let that = this;
        function inner() {
            console.log(this);
        }
        inner();
    }
};
//Output
{meth: ƒ}
Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}

Thanks in advance for demystifying


Solution

  • When you see this code:

    function inner() {
        console.log(this);
    }
    inner();
    

    It really is irrelevant whether that code occurs in another function body or not, or whether that function body belongs to a method of some object, ...etc. It is irrelevant.

    What is relevant is how you call inner. You call it not as someobject.inner(), nor with explicit binding, like inner.call(this), ... so there is no binding of this, hence you get the default binding, which is the window object when running in sloppy mode, or undefined in strict mode.

    The function outer assigned to meth seems to automatically get the this-keyword set to the surrounding object as execution context

    This is not assured. If you do:

    let outer = meth.outer;
    outer();
    

    ...then you will notice that this is getting the default binding as well. Again, it depends on how you call the function.

    If you call it with the dot-notation, then you implicitly bind it with the object:

    meth.outer();
    

    So now this will be meth in the execution context of outer.