为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

catspeake 2022-01-01 20:48:19
所以我用以下构造函数和方法创建了一个类 Complexclass 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”不可写;?
查看完整描述

1 回答

?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

使用Object.defineProperties(一次定义多个属性)和this. 该writable属性定义目标对象中定义的属性是否仅可读,默认为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;

})();


查看完整回答
反对 回复 2022-01-01
  • 1 回答
  • 0 关注
  • 204 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号