如何防止在javascript中扩展对象属性

时间:2016-11-26 07:27:19

标签: javascript javascript-objects defineproperty

我试图密封对象属性。

我的问题是,这里我给了Object.seal(personObject),这个特定的对象是密封的,不允许在这个对象中配置或进行任何扩展,但是我没有在personObject_2上提及它确实允许扩展或配置

我如何在原型上制作它。我的意思是像任何类型的人都应该/尊重这个印章。我们可以实现这样的行为



"use strict";
var personModule=(function (module) {
   var  person=function (fname,lname) {
       Object.defineProperty(this,'firstName',{
          get:function () {
            return fname;
          }
          ,set:function (newValue) {
            fname=newValue;
         },
         configurable:true
       });

       Object.defineProperty(this,'lastName',{
         get:function () {
           return lname;
         }
         ,set:function (newValue) {
           lname=newValue;
         },
         configurable:true
       });

       Object.defineProperty(this,'fullName',{
         get:function () {
           return fname+lname;
         },
         configurable:true
       });

     }
     module.person=person;
     return module;
})(personModule || {});

var personObject=new personModule.person( "Raju","Rani");
console.log(personObject.fullName);
Object.seal(personObject);
//delete personObject.firstName;-->It throws error here




var personObject2=new personModule.person( "Shiva","Kumar");

delete personObject2.firstName;

console.log(personObject2.firstName);




由于

2 个答案:

答案 0 :(得分:1)

以下是代理版本,以防您不喜欢在构造函数

上添加Object.seal



"use strict";
var personModule=(function (module) {
   var  person=function (fname,lname) {
   Object.defineProperty(this,'firstName',{
      get:function () {
        return fname;
      }
      ,set:function (newValue) {
        fname=newValue;
     },
     configurable:true
   });

   Object.defineProperty(this,'lastName',{
     get:function () {
       return lname;
     }
     ,set:function (newValue) {
       lname=newValue;
     },
     configurable:true
   });

   Object.defineProperty(this,'fullName',{
     get:function () {
       return fname+lname;
     },
     configurable:true
   });

 }
 module.person=new Proxy(person, {
     construct(target, args){
         args.unshift(null);
         let ctor = target.bind.apply(target, args);
         let result = new ctor();
         Object.seal(result);
         return result;
     }
 });
 return module;
})(personModule || {});

var personObject=new personModule.person( "Raju","Rani");
console.log(personObject.fullName);
Object.seal(personObject);
//delete personObject.firstName;-->It throws error here




var personObject2=new personModule.person( "Shiva","Kumar");

delete personObject2.firstName;

console.log(personObject2.firstName);




答案 1 :(得分:0)

你有没有尝试过 - immutable-js

var personObject = new personModule.person("Raju", "Rani");

var sealed = Immutable.Map(personObject);