简体   繁体   English

逆向工程基类定义

[英]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. 当提供其他数字时,我给出的第一个示例和第二个示例的行为各不相同,第三个示例取决于result被调用的次数,而不是传递给它的参数。

All you need is Object.getPrototypeOf , eg 您只需要Object.getPrototypeOf ,例如

Object.getPrototypeOf(MyClass) === BaseClass

ES6 class syntax sets the resulting constructor's [[Prototype]] to the parent class. ES6类语法将生成的构造函数的[[Prototype]]设置为父类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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