属性的类型

2020-11-06  本文已影响0人  ticktackkk

数据的属性

修改属性的默认特性

      let person={}
      Object.defineProperty(person,'name',{
          value:123,
      })
      console.log(person);

访问器属性

另外访问器属性不能被直接调用,必须用Object.defineProperty()
      let book = {
        year_: 2017,
        editon: 1,
      };
      Object.defineProperty(book, "year", {
        get(e) {
          return this.year_;
        },
        set(newValue) {
          if (newValue > 2017) {
            this.year_ = newValue;
            this.editon += newValue - 2017;
          }
        },
      });
      book.year = 2018;
      console.log(book);
定义多个属性Object.defineProperties

这段代码定义了两个数据属性year_和edtion还有一个访问器属性year

      let book = {
        year_: 2017,
        editon: 1,
      };
      Object.defineProperties(book, {
        year_: {
          Value: 2020,
        },
        editon: {
          value: 1,
        },
        year: {
          get() {
            return this.year_;
          },
          set(newValue) {
            if (newValue > 2017) {
              this.year_ = newValue;
              this.editon += newValue - 2017;
            }
          },
        },
      });
      book.year = 2018;
      console.log(book);
读取属性的特性Object.getOwnPropertyDescriptor
      console.log(Object.getOwnPropertyDescriptor(book,'year'));
     // configurable: false
     // enumerable: false
     // get: ƒ get()
     // set: ƒ set(newValue)
     //__proto__: Object
合并类型Object.assign()(浅拷贝)
      desc = {};
      src = {
        id: "src",
      };
      aaa = {
        ids: "aaa",
      };
      result = Object.assign(desc, src, aaa);
      console.log(result);

如果多个对象都有相同的属性,则使用最后一个赋值的值

    a = {
        value: 1,
      };
      b = {
        value: 2,
      };
      Object.assign(a, b);
      console.log(a);//value:2
对象相等及标识判定

Object.is()

     console.log(Object.is(true,1));false
     console.log(Object.is({},{})); false
     console.log(Object.is("2",2)); false
     console.log(Object.is(NaN,NaN)); true
     console.log(Object.is(+0,-0)); false
     console.log(Object.is(-0,0)); false
     console.log(Object.is(+0,0)); true
上一篇下一篇

猜你喜欢

热点阅读