Custom printing from console.log?

后端 未结 3 1262
庸人自扰
庸人自扰 2021-01-21 12:22

Let\'s say I have this class.

class Attribute {
  constructor(name) {
    this.name = name;
  }
}

And I create an instance and log it to the c

3条回答
  •  半阙折子戏
    2021-01-21 13:01

    A sane solution would probably be to use a custom logging function that stringifies Attribute values.

    However, if you have a vendetta against people who need to maintain your code in the future, one solution that meets the technical requirements of this question is to have your class extend a type that console.log automatically serializes to string, like RegExp. When you console.log a RegExp instance, Chrome (and probably other environments) automatically serializes it to its bare /.../ expression. Simply overwrite what string it should serialize to by supplying a custom toString function, and you've got exactly what you asked for.

    class Attribute extends RegExp {
      constructor(name) {
        super();
        this.name = name;
      }
      toString() {
        return this.name
      }
    }
    var test = new Attribute('Large');
    console.log(test);
    

    This is roughly equivalent to answering the question "How do I stop my house from flooding?" with "Put your house on a giant raft" instead of "Put some caulk in your basement" or "Move somewhere else." Some side effects will include:

    • Your objects will inherit regular expression properties like global and exec

    • Testing if your object is instanceof RegExp will of course return true, which might cause your object to be valid inputs for routines that only expect to operate on regular expression objects

    Using further dark magic, you can solve the these issues by doing

    Object.setPrototypeOf(Attribute.prototype, Object.prototype);
    

    immediately after your class definition, which will ensure that your this object will simply be run through the RexExp constructor (thereby flagging it for stringified log output) but not inherit from RexExp.prototype. By mixing class and prototype syntax together, you also ensure that your code is confusing and everyone is actively afraid of it.

提交回复
热议问题