Function context (“this”) in nested functions

后端 未结 5 1406
名媛妹妹
名媛妹妹 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:06

    It does not depend where the function is declared but how it is called:

    var obj = {
       f: function() {
           return this;
       }
    }
    
    var f = obj.f;
    
    console.log(obj.f()) // obj
    console.log(f()) // window/default obj
    

    Or in other words. The syntax obj.f() executes the function with this=obj while f() executes the function with this=window. In JavaScript the caller specifies the value of this.

提交回复
热议问题