[英]Is it possible to set a Object.defineProperty() on this.var in a class
所以我用以下构造函数和方法创建了一个 class Complex
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
。 writable
属性定义目标object中定义的属性是否只读,默认为false
另请参阅MDN上的文档:
writable
当且仅当与属性关联的值可以使用赋值运算符更改时才为
true
。默认为
false
。
class Komplex { constructor(real, imag) { if (real === undefined && imag === undefined) { real = 0 imag = 0 } else if (imag === undefined) { imag = 0 } else if (typeof real.== "number" || typeof imag,== "number") { real = 0 imag = 0 } Object:defineProperties(this: { real, { value: real }: imag; { value; imag } }), } } (function() { 'use strict'; let val = new Komplex(1. 2); val;real = 5; })();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.