javascript 属性描述符(descriptor)

女爷i 2022-12-18 09:54 211阅读 0赞

一、定义新属性与其描述符

  1. Object.defineProperty(o, propName, descriptor) 定义单个属性

    (1) 描述符可拥有的键值

































    描述符 configurable enumerable value writable get set
    数据描述符 X X
    存取描述符 X X

    (2) 示例

    1. let o = { };
    2. // 数据描述符属性
    3. Object.defineProperty(o, 'data1', {
    4. configurable: true,
    5. enumerable: true,
    6. writable: true,
    7. value: 10
    8. })
    9. // 存取描述符属性
    10. let data2Key = Symbol('data2');
    11. Object.defineProperty(o, 'data2', {
    12. configurable: true,
    13. enumerable: true,
    14. set: function(_value) { // 此处最好不要用箭头函数,避免数据注入到window中
    15. this[data2Key]= _value;
    16. },
    17. get: function() {
    18. return this[data2Key];
    19. }
    20. })
    21. // 存取描述符的便捷写法(这种写法configurable与enumerable默认为true)
    22. o = {
    23. set data2(_value){
    24. this[data2Key]= _value;
    25. },
    26. get data2(){
    27. return this[data2Key];
    28. }
    29. }

    (3) configurable: false

    1. 该属性不能在数据描述符和存取描述符间切换
    2. 不能删除属性(delete 无效)
    3. 允许define一个描述符一模一样的
    4. 允许writable 从true修改为false
    5. writable: true 时允许修改 value

    (4) writable: false

    1. let o = { };
    2. Object.defineProperty(o, 'data', {
    3. writable: false,
    4. value: 10
    5. })
    6. o.data = 11;
    7. console.log(o.data);
    8. // 1. 普通模式下修改o.data不会抛出错误,但修改无法完成 o.data打印10
    9. // 2. 严格模式下会报错 Uncaught TypeError: Cannot assign to read only property 'data' of object

    (5) 一个属性的描述符不能同时是数据描述符与存取描述符。换言之,一个属性的描述符中不能同时设置了(value, writable) 与 (get, set)。(ps: ( (设置value || 设置writable) && (设置get || 设置set) ) => Error

  2. Object.defineProperties(o, props) 定义多个属性

    1. props: {
    2. prop1: {
    3. configurable: false,
    4. ...
    5. }
    6. }

二、 获取属性的描述符

  1. // 测试数据定义
  2. let symbolKey = Symbol('symbolKey');
  3. function Obj(){
  4. this.ownKey = 1;
  5. this[symbolKey] = 2;
  6. }
  7. Obj.prototype.prototypeKey = 3;
  8. let o = new Obj();
  9. Object.defineProperty(o, 'unenumerableKey', {
  10. enumerable: false,
  11. value: 4
  12. })
  1. Object.getOwnPropertyDescriptor(o, prop) 获取对象单个本地属性的描述符

    1. Object.getOwnPropertyDescriptor(o, symbolKey);
    2. // {value: 2, writable: true, enumerable: true, configurable: true}
  2. Object.getOwnPropertyDescriptors(o) 获取对象全部本地属性的描述符

    1. Object.getOwnPropertyDescriptor(o);
    2. /* { ownKey: {value: 1, writable: true, enumerable: true, configurable: true} unenumerableKey: {value: 4, writable: false, enumerable: false, configurable: false} Symbol(symbolKey): {value: 2, writable: true, enumerable: true, configurable: true} } */

发表评论

表情:
评论列表 (有 0 条评论,211人围观)

还没有评论,来说两句吧...

相关阅读