【发布时间】:2018-08-03 18:52:49
【问题描述】:
我需要一些关于 typescript 类的解释,因为我有一些我不明白的东西。例如,我有一个具有一些属性的“汽车”类:
export class Car {
private _id: number;
private _brand: string;
private _model: string;
constructor(car) {
if (car) {
this.id = car.id;
this.brand = car.brand; // should be this.brand or this._brand ?
this.model = car.model;
}
}
set id(value: number) {
this._id = value;
}
get id(): number {
return this._id;
}
set brand(value: number) {
this._brand = value;
}
get brand(): number {
return this._brand;
}
set model(value: number) {
this._model = value;
}
get model(): number {
return this._model;
}
}
我必须将此对象发送到 API。这个接受“品牌”和“型号”,而不是“_brand”或“_model”。那么如何将好的模型发送到 API 呢?
所以当我通过 console.log 显示汽车对象时,我有什么:
汽车{ id:“1”,品牌:“Porsche”,型号:“Carrera”,_id:“1”,_brand:“Porsche”,_model:“Carrera”}
如果我删除“_brand”,“brand”值未定义,但我想保留它。
delete myCar['_brand'];
console.log(myCar); // Car {_id:"1", "brand": undefined ...}
【问题讨论】:
-
是的,你是对的 :) 非常感谢