Function context (“this”) in nested functions

后端 未结 5 1270
名媛妹妹
名媛妹妹 2021-02-09 17:26

When you invoke a top-level function in Javascript, the this keyword inside the function refers to the default object (window if in a browser). My understanding is that

5条回答
  •  鱼传尺愫
    2021-02-09 18:00

    You can call any function that is in scope with functionName(). Since you haven't called it on an object, it will be called in the context of the default object (window). (IIRC, it will be called in the context of undefined if you are in strict mode).

    The default object for context has nothing to do with where a function is defined or what scope that function appears in. It is simply the default object.

    If a function is a property of an object, you can call it as reference.to.object.function(), and it will be called in the context of object instead of the default object.

    Other things that change the context are the new keyword and the apply, call, and bind methods.

提交回复
热议问题