上课:
class Something {
constructor(something) {
this._something = something;
}
get something() {
return this._something;
}
}
我希望能够将访问器值传播到一个新对象中,例如:
const somethingObject = new Something(12);
const somethingSpread = { ...somethingObject };
但是,它仅输出类的_something
属性:
{ _something: 12 }
但是我要寻找的是这样的:
{ something: 12 }
我还尝试了Object.assign
,它的输出与上面相同:
const somethingAssigned = Object.assign({}, somethingObject);
// Output: { _something: 12 }
有可能做到这一点吗?
答案 0 :(得分:0)
只需尝试:
class Something {
private _something: Number;
constructor(something: Number) {
this._something = something;
}
public get something(): Number {
return this._something;
}
public set something(value: Number) {
this._something = value;
}
}
function shallowClone(obj) {
return Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
);
const var1 = new Something(12);
const var2 = shallowClone(var1);
console.log(var1, var1.something);
console.log(var2, var2.something);
输出:
某事{_something:12} 12
{_something:12} 12