Javascript 是否可以在类中的this.var上设置Object.defineProperty()
因此,我用以下构造函数和方法创建了一个类复合体Javascript 是否可以在类中的this.var上设置Object.defineProperty(),javascript,Javascript,因此,我用以下构造函数和方法创建了一个类复合体 class Komplex { constructor(real, imag) { if (real === undefined && imag === undefined) { real = 0 imag = 0 this.real = real this.imag = imag } else if (imag === undefined) { thi
class Komplex {
constructor(real, imag) {
if (real === undefined && imag === undefined) {
real = 0
imag = 0
this.real = real
this.imag = imag
} else if (imag === undefined) {
this.real = real
this.imag = 0
} else if (typeof real === "number" && typeof imag === "number") {
this.real = real
this.imag = imag
} else {
real = 0
imag = 0
this.real = real
this.imag = imag
}
}
}
所以我的问题是如何使“this.real”和“this.imag”不能用Object.defineProperty()编写 使用
Object.defineProperties
(一次定义多个属性)和this
。writeable
属性定义目标对象中定义的属性是否仅可读,默认为false
另见以下文件:
可写
true
当且仅当与属性关联的值可以通过赋值运算符更改时
默认值为false
class-Komplex{
构造函数(real,imag){
if(real==未定义&&imag==未定义){
实数=0
imag=0
}else if(imag==未定义){
imag=0
}else if(typeof real!=“number”| typeof imag!=“number”){
实数=0
imag=0
}
对象。定义属性(此{
真实:{
价值:真实
},
图像:{
值:imag
}
});
}
}
(功能(){
"严格使用",;
设val=new-Komplex(1,2);
val.real=5;
})();
this#real=stuff
(私有属性,它们接近于被指定)您可以通过使用:constructor(real=0,imag=0){this.real=real;this.imag=imag;}
至少:this.real=typeof real=='number'?真实值:0代码>。对于imag
…我已经创建了一个类复合体。。。失败<代码>类Komplex
类Komplex{constructor(real,imag){Object.defineProperties(this,{real:{value:real | | 0},imag:{value:imag | | | 0}}}