ES5中Object的扩展

发布于 2020-07-02  92 次阅读


  • Object.create(prototype,[descriptor])
  • "use strict";
    var student={
        school:"xxx High School",
        name:"xxx",
        position(){
            console.log(this.name+"的职务是"+this.type);
        }
    };
    var mintor=Object.create(student,{
        type:{
            value:"班长",
            wirtable:false,
            configurable:false,
            enumerable:true
        },
        name:{
            value:"jpc",
            writable:true,
            configurable:true,
            enumerable:true
        },
        getName:{
            value:()=>{
                return this.name;
            },
            writable:false,
            configurable:false,
            enumerable:false
        }
    });
    console.log(mintor);
  • Object.defineProperty(object,prop,descriptor)
  •   var student={
          name:"jpc"
      };
      Object.defineProperty(student,"age",{
          value:19,
          writable:true,
          configurable:true,
          enumerable:true
      })
      console.log(student);
  • Object.defineProperties(object,descriptors)
  •   var student={
          firstName:"牛",
          lastName:"一一"
      };
      Object.defineProperties(student,{
          fullName:{
              get:function (){
                  return this.firstName+this.lastName;
              },
              set:function (data){
                  this.firstName=data[0];
                  this.lastName=data[1];
              }
          }
      });
      console.log(student.fullName);
  • 简化写法
  •   var student={
          firstName:"牛",
          lastName:"一一",
          get fullName(){
              return this.firstName+this.lastName;
          },
          set fullName(data){
              this.firstName=data[0];
              this.lastName=data[1];
          }
      };
      console.log(student.fullName);

    一个人只有亲眼看到自己伤疤的时候才知道什么是痛,什么是对与错。