TypeScript/JavaScript 中是否有選項可以使用 getter 列印具有私有屬性的物件,而不是列印私有屬性名稱。
例如,我在 TypeScript 中有這個類
class Vehicle {
constructor(private _brand: string, private _year: number) {}
get brand(): string {
return this._brand;
}
get year(): number {
return this._year;
}
set year(year: number) {
this._year = year;
}
set brand(brand: string) {
this._brand = brand;
}
}
const vehicle: Vehicle = new Vehicle('Toyota', 10);
console.log(vehicle);
我懂了
[LOG]: Vehicle: {
"_brand": "Toyota",
"_year": 10
}
但我想知道我是否能得到這樣的東西
[LOG]: Vehicle: {
"brand": "Toyota",
"year": 10
}
uj5u.com熱心網友回復:
什么console.log因環境而異。如果你想做你所描述的,你必須撰寫你自己的記錄器函式,例如(在 JavaScript 中,但型別很容易添加)見評論:
function log(obj) {
// Get the names of getter properties defined on the prototype
const ctor = obj.constructor;
const proto = ctor?.prototype;
const names = new Set(
proto
? Object.entries(Object.getOwnPropertyDescriptors(proto))
.filter(([_, {get}]) => !!get)
.map(([name]) => name)
: []
);
// Add in the names of "own" properties that don't start with "_"
for (const name of Object.keys(obj)) {
if (!name.startsWith("_")) {
names.add(name);
}
}
// Create a simple object with the values of those properties
const simple = {};
for (const name of names) {
simple[name] = obj[name];
}
// See if we can get a "constructor" name for it, apply it if so
let objName =
obj[Symbol.toStringTag]
|| ctor?.name;
if (objName) {
simple[Symbol.toStringTag] = objName;
}
// Log it
console.log(simple);
}
現場示例:
顯示代碼片段
"use strict";
function log(obj) {
// Get the names of getter properties defined on the prototype
const ctor = obj.constructor;
const proto = ctor?.prototype;
const names = new Set(
proto
? Object.entries(Object.getOwnPropertyDescriptors(proto))
.filter(([_, {get}]) => !!get)
.map(([name]) => name)
: []
);
// Add in the names of "own" properties that don't start with "_"
for (const name of Object.keys(obj)) {
if (!name.startsWith("_")) {
names.add(name);
}
}
// Create a simple object with the values of those properties
const simple = {};
for (const name of names) {
simple[name] = obj[name];
}
// See if we can get a "constructor" name for it, apply it if so
let objName =
obj[Symbol.toStringTag]
|| ctor?.name;
if (objName) {
simple[Symbol.toStringTag] = objName;
}
// Log it
console.log(simple);
}
class Vehicle {
constructor(_brand, _year) {
this._brand = _brand;
this._year = _year;
}
get brand() {
return this._brand;
}
get year() {
return this._year;
}
set year(year) {
this._year = year;
}
set brand(brand) {
this._brand = brand;
}
}
const vehicle = new Vehicle('Toyota', 10);
log(vehicle);
有很大的空間來調整你喜歡它的方式,這只是你可能如何去做的一個草圖。
uj5u.com熱心網友回復:
我認為沒有辦法做到這一點,但您可以在類中創建一個 log 方法,如下所示:
log() {
console.log({
brand: this.brand,
year: this.year,
});
}
然后只需呼叫 vehicle.log();
然后你會得到這樣的日志 {brand: 'Toyota', year: 10}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/381602.html
標籤:javascript 打字稿 哎呀
上一篇:如何使用智能合約獲得正確的余額?
