[JS-ES5 Protected Objects]

Posted by NathanS on Mon, 20 May 2019 05:57:30 +0200

Preface

You know, the attributes of objects also have attributes!

The common attributes of objects in js can be changed to any value at any time, new attributes can be added at any time, and can be deleted at any time.

This is because the property of the object is operable by default, and by modifying the property of the object property, we can set the operability of the property of the object.

Our goal is to protect objects and attributes.

Review Object.create():

Based on a parent object, a child object is created and new attributes are extended for the child object.
Var son = Object. create (parent object,){
    Extended attribute name 1::{
        Writtable: true, // is modifiable and can be omitted
        Value: attribute value,
        configurable:true // can be set and omitted
    },
    Extended attribute name 2: {...}
});

Protection attribute

Attributes are divided into:

Named Properties: Available. Accessed Properties
 Data attributes: attributes that store attribute values directly

Each attribute has four characteristics:

value: Actual storage of attribute values
 Writtable: Can I change the default to true?
enumerable: Can it be traversed to default true for in
   You can only control for in, not access.
configurable: Is it possible to modify other features
              Can you delete this property?

Obtain four characteristics:

var attrs=Object.getOwnPropertyDescriptor(obj,"Attribute name");

Set four features:

Object.defineProperty(obj, "attribute name",,{
   Characteristics: value,
})
Question: Four features that can only modify one attribute at a time
 Solution: Four characteristics of modifying multiple attributes at the same time?
Object.defineProperties(obj,{
     Property name: {property: value,...},
      ... : ...
})

Question: If the attributes to be modified do not exist?

Answer: This property is automatically created: 
Emphasize: 
With the properties added by defineProperty, all four features default to false!
By adding attributes directly to the object, the default values of the four features are true!

Question: Four major features can only provide basic protection for attributes. How to use custom rules to protect attributes

Accessor attributes: Special attributes that do not store attribute values directly and specifically protect other attributes
 Why: The four major features of data attributes cannot be protected using custom rules
 When: As long as you use custom rules to protect attributes
 How to: Step 2:
1. Define a closure structure that actually stores attribute values
 2. Define an accessor property to protect local variables in the closure, as follows:
+function(){
    var variable;
    Object.defineProperty(obj,"Attribute name",{
        get:function(){
            returnvariable;
        },
        set:function(val){
            //Variable =val;
        },
        enumerable:true/false,
        configurable:true/false
    })
}();
//Customize features to set accessor properties
//Anonymous function self-tuning
var eric={id:1001,ename:"Eric"};
+function(){
    var _age;
    Object.defineProperty(eric,"age",{
        get:function(){return _age;},//get(){},
        set:function(val){
            if(val>=18&&val<=65) _age=val;
            else throw new Error("Age between 18~65 Between")
        }
    })
}();
eric.age=20;
console.dir(eric);
console.log(eric.age);

Problem: Protected data cannot be stored in common data attributes

Because data attributes can be accessed at will!
Solve: 
    Internal attributes: Not allowed. Accessed attributes
    For example: class__proto__

Protected object

Providing security for the entire object: tamper-proof

Three levels:

1. Anti-Extension: Do not add new attributes to objects

Object.preventExtensions(obj);

2. Sealing: That is to prevent expansion, and prohibit deletion of any attributes

Object.seal(obj);
2 Thing: 1,Anti expansion
      2,For all attributes configurable Are set to false!

3. Freezing: It prevents expansion, prohibits deletion, and prohibits modification of all attribute values.

Object.freeze(obj);
3 Thing: 1,Anti expansion
      2,For all attributes configurable Are set to false!
      3,For all attributes writable Are set to false
//The most rigorous constructor, employee type
function Emp(ename,id,salary,age){
    this.ename=ename;
    this.id=id;
    this.salary=salary;
    var _age;
    Object.defineProperties(this,{
        id:{writable:false},
        salary:{enumerable:false},
        age:{
            set(val){
                if(val>=18&&val<=65) _age=val;
                else throw new Error("Age between 18~65 Between")
            },
            get(){return _age},
            enumerable:true //Notice here 
//New properties created with. are modified by defineProperty/defineProperties with a default value of true
//New attributes added with defineProperty/defineProperties, the default value of which is false
        }
    })
    this.age=age;
    //Anti-extensibility: (No new attributes added) (extensible: false)
   //Set the current new object to prohibit the extension of new properties
   //Object.preventExtensions(this);
    //Sealed, non-expandable, and non-removable (configurable:false)
    Object.seal(this);
    //Freeze, sealed and non-modifiable (wretable=false)
    //Object.freeze(this);
}
var Lisi=new Emp("lisi",101,10000,24);
var Hanmei=new Emp("hanmei",102,13000,26);
var Zhaoyun=new Emp("zhaoyun",103,18000,29);
//Zhaoyun.age=78;//Error
for(var key in Zhaoyun)console.log(Zhaoyun[key]);
console.dir(Lisi);
console.dir(Hanmei);
console.dir(Zhaoyun);

Strict mode

A new execution mode that is stricter than the normal js execution mode

When: Strict mode should be enabled for almost all new project js files

How to: Two

1. New project: at the beginning of each js file: "use strict"; let the entire js file start strict mode
 2. Old projects: function-by-function startup

Topics: Attribute