gpt4 book ai didi

javascript - 是否可以在类中的 this.var 上设置 Object.defineProperty()

转载 作者:行者123 更新时间:2023-11-30 19:07:00 25 4
gpt4 key购买 nike

所以我创建了一个具有以下构造函数和方法的 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
}
}
}

所以我的问题是如何使用 Object.defineProperty() 使“this.real”和“this.imag”不可写; ?

最佳答案

Object.defineProperties(一次定义多个属性)与 this 一起使用。 writable 属性定义目标对象中定义的属性是否只可读,默认为false

另请参阅 MDN 上的文档:

writable

true if and only if the value associated with the property may be changed with an assignment operator.

Defaults to 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;
})();

关于javascript - 是否可以在类中的 this.var 上设置 Object.defineProperty(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58877165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com