头图

Preface

Now there is such a demand: use an object to store the results of each subject of a certain student, requiring that only the subject scores can be changed each time, and no more subjects can be added or deleted.

Analyze, this requirement is actually the need to create an object with fixed attributes, whose attributes cannot be added or deleted, but the attribute values can be changed.

Some students may start like this:

  • First, define an object that meets the requirements:
// 声明成绩存储对象
let reportObj = {};
// 给成绩存储对象添加科目,并设置科目属性不可增删,但科目成绩可修改
Object.defineProperties(reportObj, {
    ChineseMark: {
        enumerable: true,
        writable: true,
        configurable: false,
        value: 60
    },
    EnglishMark: {
        enumerable: true,
        writable: true,
        configurable: false,
        value: 60
    }
});
  • Then write the score:
// 存入科目成绩
reportObj.ChineseMark = 99;
reportObj.EnglishMark = 95;
console.log(reportObj);  // {ChineseMark: 99, EnglishMark: 95}

Try deleting the attribute:

delete reportObj.ChineseMark;  // false
console.log(reportObj);  // {ChineseMark: 99, EnglishMark: 95}

It seems that the conditions are indeed met, so try adding attributes again:

reportObj.PhysicsMark = 100;
console.log(reportObj);  // {ChineseMark: 99, EnglishMark: 95, PhysicsMark: 100}

What's the matter, why suddenly it doesn't meet the requirements? Object.defineProperties() can only precisely control the characteristics of the added attributes, but if you add attributes to the object, it cannot control it.

Today we will use a simple interface method to implement this moth demand ︿( ̄︶ ̄)︿

Object.seal()

describe

If seal is used as a verb, its interpretation is "seal":

image-20210825210254120

As the name implies, the Object.seal() method is used to "seal" an object. It prevents the object from adding new attributes and marks all existing attributes of the object as unconfigurable. The value of the current attribute can be changed as long as it is originally writable.

effect

Usually, an object is extensible (new attributes can be added).

Sealing an object will make it impossible to add new properties, and all existing properties will become non-configurable. The effect of attribute non-configurability is that the attribute becomes non-deletable, and a data attribute cannot be redefined as an accessor attribute, or vice versa. But the value of the attribute can still be modified.

Try to delete the attributes of a sealed object or convert the attributes of a sealed object from a data attribute to an accessor attribute, and the result will silently fail or throw a TypeError (the most common in strict mode, but not the only one).

const object1 = {
    property1: 42
};

Object.seal(object1);
object1.property1 = 33;
console.log(object1.property1);
// expected output: 33

delete object1.property1; // cannot delete when sealed
console.log(object1.property1);
// expected output: 33

In summary, Object.seal() actually does the following:

  • Set Object.preventExtension() to prohibit adding new properties (absolutely exist)
  • Set configurable to false, prohibit configuration (absolutely exist)
  • Prohibit changing accessor properties (getter and setter)

grammar

Object.seal(obj)

parameter

The parameter obj represents the object to be sealed.

return value

The sealed object.

Fulfill the demand

Since there is such a useful method, of course we have to make good use of it, and finally we can perfectly fulfill the requirements at the beginning of the article:

// 声明成绩存储对象及其属性
let reportObj = {   
    ChineseMark: 60,
    EnglishMark: 60
};
// 密封成绩对象
let sealedReportObj = Object.seal(reportObj);
// 更改科目分数
sealedReportObj.ChineseMark = 99;
sealedReportObj.EnglishMark = 97;
console.log(sealedReportObj); // {"ChineseMark": 99, "EnglishMark": 97}

Verify it:

// 增加属性
sealedReportObj.PhysicsMark = 100;
console.log(sealedReportObj); // {"ChineseMark": 99, "EnglishMark": 97}

// 删除属性
delete sealedReportObj.ChineseMark; // false
console.log(sealedReportObj); // {"ChineseMark": 99, "EnglishMark": 97}

It can be seen that the attributes of the object cannot be added or deleted. It is a simple realization of the requirements.

Expand

If we want to judge whether an object is "sealed", we can use the Object.isSealed() method:

Object.isSealed(sealedReportObj); // true

Object.freeze()

Seeing this, many students may have thought of the Object.freeze() method, which is used to freeze an object. The actual effect is literally: to freeze an object so that its properties and property values cannot be changed. It is obviously inappropriate to achieve this requirement.

Common ground

Object.seal() and Object.freeze() have the following in common:

  • The object of action becomes non-extensible, which means that no new properties can be added.
  • Every element in the affected object becomes non-configurable, which means that the attribute cannot be deleted.
  • If used in'use strict' mode, both methods may throw errors.

difference

Object.seal() allows you to modify the value of an attribute, but Object.freeze() cannot.

Summarize

The above is a brief introduction and application Object.seal() Object.freeze() , I hope it can be helpful to everyone.

~

~ End of this article, thanks for reading!

~

Learn interesting knowledge, meet interesting friends, and create interesting souls!

Hello everyone, I is [ programming Samadhi 〗 author hermit king , my public number is " programming Samadhi " welcome attention, we hope the exhibitions!

Come, with expectations, I have Moxiang to greet you! You return, regardless of gains or losses, only with the lingering rhyme as a gift!

Pay equal attention to knowledge and skills, both internal and external skills, both theory and practice must be grasped, and both hands must be hard!

Reference documents:

Object.seal()

Object.freeze()


编程三昧
54 声望10 粉丝

学习有趣的知识,交识有趣的朋友,造就有趣的灵魂!