TypeScript-getOwnPropertyNames()-构造函数属性与Getter/Setter
我对打字很陌生,有一点我不太明白 想象一下以下几类:TypeScript-getOwnPropertyNames()-构造函数属性与Getter/Setter,typescript,reflection,Typescript,Reflection,我对打字很陌生,有一点我不太明白 想象一下以下几类: export class PropertyInConstructor { constructor(public foo: boolean) { } } 据我所知,这两种方法都为我提供了一个属性,我可以使用newpropertyinconstructor().foo或newpropertyWithGetSet().foo访问该属性 现在,我想获得此类(无实例!)的现有属性,并尝试一下: console.log(Object.ge
export class PropertyInConstructor {
constructor(public foo: boolean) {
}
}
据我所知,这两种方法都为我提供了一个属性,我可以使用
newpropertyinconstructor().foo
或newpropertyWithGetSet().foo
访问该属性
现在,我想获得此类(无实例!)的现有属性,并尝试一下:
console.log(Object.getOwnPropertyNames(PropertyInConstructor.prototype));
console.log(Object.getOwnPropertyNames(PropertyWithGetSet.prototype));
[“构造函数”][“构造函数”、“foo”] 为什么在构造函数中指定属性的调用没有添加“foo”属性
是否缺少某些内容或以其他方式获取这些属性?简短回答:大多数属性都是在运行时动态添加到实例中的。需要将带有getter和setter的属性添加到带有
对象的原型中。defineProperty
在运行时添加
第一个例子是:
export class PropertyInConstructor {
constructor(public foo: boolean) {
}
}
该属性仅在构造函数运行时添加到实例中。以下是传输的JavaScript:
var PropertyInConstructor = /** @class */ (function () {
function PropertyInConstructor(foo) {
this.foo = foo;
}
return PropertyInConstructor;
}());
实际上,在构造函数运行之前,类上不存在属性foo
这不仅适用于构造函数属性,还适用于所有未根据原型定义的属性,例如:
class PropertyInConstructor {
public foo: boolean;
constructor() {
this.foo = true;
}
}
定义属性
使用get和set时,情况有所不同,因为该属性已添加到原型中:
var PropertyWithGetSet = /** @class */ (function () {
function PropertyWithGetSet() {
this._foo = false;
}
Object.defineProperty(PropertyWithGetSet.prototype, "foo", {
get: function () {
return this._foo;
},
set: function (theFoo) {
this._foo = theFoo;
},
enumerable: true,
configurable: true
});
return PropertyWithGetSet;
}());
就我所知,第一个示例没有创建getter/setter对。第二个示例实际上定义了原型的属性,如果将示例复制到
var PropertyWithGetSet = /** @class */ (function () {
function PropertyWithGetSet() {
this._foo = false;
}
Object.defineProperty(PropertyWithGetSet.prototype, "foo", {
get: function () {
return this._foo;
},
set: function (theFoo) {
this._foo = theFoo;
},
enumerable: true,
configurable: true
});
return PropertyWithGetSet;
}());