简体   繁体   中英

JavaScript: How to call STATIC method on superclass but the method isnot defined on the derivated class?

I have these classes:

 class Control { static Code = 3; static GetCodeChain() { var result = []; result.push(this.Code); if (super.GetCodeChain) { result = result.concat(super.GetCodeChain()); } return result; } } class SubControl extends Control { static Code = 2; } class AnotherControl extends SubControl { static Code = 1; } console.log(AnotherControl.GetCodeChain()); // prints 1, but I want [1,2,3]

I cannot write the methods on the subclasses.

How to call the STATIC method on the superclass properly?

I think I found a solution:

 class Control { static Code = 3; static GetCodeChain() { var result = []; for (var proto = this; proto; proto = Object.getPrototypeOf(proto)) { if (proto.Code) { result.push(proto.Code);} } return result; } } class SubControl extends Control { static Code = 2; } class AnotherControl extends SubControl { static Code = 1; } console.log(AnotherControl.GetCodeChain()); //prints [1,2,3]

Using "Object.getPrototypeOf(this)" I can access the superclass even on an static context. On this context, "this" is the derivated class itself. No instances are involved on this solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM