What is the rationale for the behavior of the 'this' keyword in JavaScript?

前端 未结 7 825
感动是毒
感动是毒 2020-12-13 00:59

I am asking this from a language design point of view. So I am trying to find out

  1. What is the rationale for the behavior of this?
  2. To what
7条回答
  •  生来不讨喜
    2020-12-13 01:46

    You seem to be expecting this to behave as it does in certain OO languages, where it always refers to the object a method belongs to.

    But in JavaScript, a function can be attached to multiple objects, or no object at all. In your example, you've written a function intended to be used in the context of one specific object... But nothing prevents me from taking that function and attaching it to any other object. That's just the nature of the language - functions are first-class, object membership is optional.

    Therefore, this refers to the context in which a function is called. Right now, that's either an arbitrary object (specified via ., .apply, or .call()) or the global object. In future versions of the language, it will refer to the context in which the function was defined: the global object for global functions, the outer this for inner functions; you can view this as a correction of a design flaw, as in practice being able to refer to the global object using this was not particularly useful.

提交回复
热议问题