Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

javascript - ES6: this within static method

Let's say I have two ES6 classes like this:

class Base {
    static something() {
        console.log(this);
    }
}

class Derived extends Base {
}

And then I make a call like this:

Derived.something();

Note that I am making a call to a static method defined on the super class via sub class.

This does not give me errors. It prints

[Function: Derived]

So accessing this within a static method seems to work here.

I need a common static method for all sub-classes of a super class and I need to be able to know what sub-class is calling this method.

Now my question is whether using this within a static method is legal. I know these static methods become class methods, and hence this would naturally point to the class object they are called on. (The class object being the constructor.)

But I can't seem to find any definitive resource that states that this is allowed by the ES specification.

This looks like a good introduction to ES6 classes but does not talk about this with static.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...