Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否可以在类中的this.var上设置Object.defineProperty()_Javascript - Fatal编程技术网

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}}}