简体   繁体   中英

Reverse engineering base class definition

In one of the puzzles I'm solving now there is a task to determine the base class for the class below

class MyClass extends BaseClass {
    result(a, b) {
        this.a = a;
        this.b = b;
        return 100 - this.a + this.b;
    }
}
let m = new MyClass();
m.result(10, 20) === 90;
m.result(20, 10) === 110;

I don't need ready solving, I need an explanation how can I get possible base class definition.

It could be this:

class BaseClass {
  set a(v) { this._a = 30-v }
  get a( ) { return this._a }

  set b(v) { this._b = 30-v }
  get b( ) { return this._b }
}

or this:

class BaseClass {
  set a(v) { this._b = v }
  get a( ) { return this._a }

  set b(v) { this._a = v }
  get b( ) { return this._b }
}

There are countably infinite many ways to achieve this:

 class BaseClass { constructor ( ) { this.i = -1; } set a(v) { this.i++; } get a( ) { return (2-this.i)*10 } set b(v) { } get b( ) { return (this.i+1)*10 } } class MyClass extends BaseClass { result(a, b) { this.a = a; this.b = b; return 100 - this.a + this.b; } } let m = new MyClass(); console.log( m.result(10, 20) === 90 ); console.log( m.result(20, 10) === 110 ); 

One more example and expected output could greatly narrow down the family of solutions. The first and second example I gave behave differently from each when other numbers are provided, and the third one depends on the number of times result has been called rather than the arguments passed into to it.

All you need is Object.getPrototypeOf , eg

Object.getPrototypeOf(MyClass) === BaseClass

ES6 class syntax sets the resulting constructor's [[Prototype]] to the parent class.

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