gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:38:27 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com