ES6: this within static method

眉间皱痕 提交于 2019-11-29 12:09:25

Under typical circumstances, the this in any call to something.method() will refer to something as long as the function is not an arrow function, bound function, or something like that (and it is neither of those in this case).

Class inheritance, or even ES6, aren't really relevant here. All you need to know is that you are calling Derived.something(), so this will refer to Derived.

Yes, this is legal in static methods, that's the way this should be done.

this refers to class instance in prototype methods and refers to class constructor in static methods, unless a method was unbound from its original context.

Similarly, super refers to parent class prototype in instance methods and refers to parent class constructor in static methods.

As long as the static method is invoked as a member expression, e.g.

Derived.something();

as opposed to

const { something } = Derived;
something();

then this will refer to Derived. Derived.something() is identical to something.call(Derived) if Derived.something is stored to an intermediate variable, because that's how a member expression with a nested call expression is evaluated, essentially.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!