javascript - 带有 typescript : what determines how an object is rendered?的vscode调试器

标签 javascript typescript visual-studio-code console.log vscode-debugger

我正在使用 vscode 编写一些 typescript ,并且我设置了一个断点。当我打开 Debug Pane 并要求它评估一个对象时,它在做什么来生成字符串表示?
我问的原因是因为我正在使用 this solution控制方式console.log呈现一个类的实例,它工作得很好——但它似乎不会影响对象在调试器中的呈现方式。
更具体地说,下面的代码(也可在 typescript 沙箱 here 中获得)会从 console.log 产生所需的输出。但是,当我在 console.log 之前设置断点时线和评估myObj在调试器中,显示的是

cls {property: 'property', hello: 'override', newProperty: 'new property'}
而不是
Greeter3Generated {property: 'property', hello: 'override', newProperty: 'new property'}
有问题的代码:
function classDecorator3<T extends { new (...args: any[]): {} }>(
  constructor: T
) {
  const cls = class extends constructor {
    newProperty = "new property";
    hello = "override";
  };
  Object.defineProperty(cls, 'name', {
    get: () => `${constructor.name}Generated`
  });
  return cls
}

@classDecorator3
class Greeter3 {
  property = "property";
  hello: string;
  constructor(m: string) {
    this.hello = m;
  }
}

const myObj = new Greeter3("world")
console.log(myObj);
//=>  Greeter3Generated: { "property": "property", "hello": "override", "newProperty": "new property" } 

最佳答案

您需要定义 Symbol.toStringTag .此外,您可以删除覆盖 native constructor.name 的 hack。 :

function classDecorator3<T extends { new (...args: any[]): {} }>(
  constructor: T
) {
  return class extends constructor {
    newProperty = "new property";
    hello = "override";
    [Symbol.toStringTag] = `${constructor.name}Generated`;
  };
}

@classDecorator3
class Greeter3 {
  property = "property";
  hello: string;
  constructor(m: string) {
    this.hello = m;
  }
}

const myObj = new Greeter3("world");
console.log(myObj);
//=>  Greeter3Generated: { "property": "property", "hello": "override", "newProperty": "new property" } 
使用纯 JavaScript 的演示(在打开开发者工具的情况下执行):

function classDecorator3(
  constructor
) {
  return class extends constructor {
    newProperty = "new property";
    hello = "override";
    [Symbol.toStringTag] = `${constructor.name}Generated`;
  };
}

const GeneratedClass = classDecorator3(class Greeter3 {
  property = "property";
  hello;
  constructor(m) {
    this.hello = m;
  }
});

const myObj = new GeneratedClass("world");
console.log(myObj);
debugger;

在 Node.js 中的结果:
Result in Node.js

关于javascript - 带有 typescript : what determines how an object is rendered?的vscode调试器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64491766/

相关文章:

javascript - 在 v-for 中创建局部变量

javascript - 嵌入式 booking.com 无法正常显示

visual-studio-code - 使用 Visual Studio Code 的 REST 客户端扩展发出 POST 请求

javascript - CSS中设置的圆半径,如何通过JS获取值?

javascript - setTimeout 加速多个选项卡

javascript - 使用 JavaScript 更改输入字段焦点的颜色

regex - VSCode : TextMate Regex in User Settings

javascript - 如何在 OpenCV.js 中获取轮廓 Angular 点的坐标?

angular - 在 angular2-material-datepicker 中设置区域设置

java - VScode 扩展错误,java 运行时无法定位在 linux 的窗口子系统上