'this' object can't be accessed in private JavaScript functions without a hack?

后端 未结 3 1010
北海茫月
北海茫月 2020-12-10 07:09

I was working on a project for a while, trying to figure out what I was doing wrong, when I finally narrowed \"the bug\" down to the fact that the below code doesn\'t work a

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 07:16

    From JavaScript: The Definitive Guide, 5th Edition (the rhino book):

    When a function is invoked as a function rather than as a method, the this keyword refers to the global object. Confusingly, this is true even when a nested function is invoked (as a function) within a containing method that was invoked as a method: the this keyword has one value in the containing function but (counterintuitively) refers to the global object within the body of the nested function.

    Note that this is a keyword, not a variable or property name. JavaScript syntax does not allow you to assign a value to this.

    Two things to pay attention to here:

    1. this isn't a variable, so the normal closure capture rules don't apply.
    2. this is "rebound" on every functiion calls, whether as a method, a normal function call, or via new. Since you're doing a normal function call (when calling Beta), this is getting bound to the "global object".

提交回复
热议问题