Scope of this in javascript function

前端 未结 3 869
灰色年华
灰色年华 2021-01-20 13:42

If you have the following code:

var global = this;
function A () {
    function B () {
        return this;
    }
    return B();
}
var C = new A();
C === gl         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-20 14:16

    The value of this is determined upon every function call. Because B is called without any context, the value of this is the global object.

    It's possible to preserve this in an outer context by simply copying it:

    function A() {
      var x = this;
      function B() {
        return x;
      }
      return B();
    }
    

提交回复
热议问题