JS Object constructor Object.freeze

JS Object constructor Object.freeze

Overview

Object.freeze(obj) can freeze an object. A frozen object can no longer be modified;

If an object is frozen, you cannot add new properties to it, delete existing properties, modify the enumerability, configurability, and writability of existing properties, or modify the values ​​of existing properties.

In addition, after freezing an object, the prototype of the object cannot be modified. freeze() returns the same object as the argument passed in.

JavaScriptDemo: Object.freeze()

const obj = {
  Prop: 42
}
Object.freeze(obj)

obj.prop = 33 // Strict mode will throw an error.

console.log(obj.prop) // 42

Example

1) Freeze Object

var obj = {
  prop: function() {},
  foo:'bar'
}

// Both the object passed as a parameter and the returned object are frozen // so there is no need to save the returned object (because both objects are equal)
var o = Object.freeze(obj)
o === obj // true

// Any changes from now on will have no effect obj.foo = 'he' // Do nothing Obj.hxx = 'he' // Do not add this property // Try to change the property via Object.defineProperty // Both of the following statements will throw an exception Object.defineProperty(obj,'foo',{value:'yy'})
Object.defineProperty(obj,'sex',{value:'女'})

// The prototype cannot be changed either // The following two statements will throw an exception Object.setPrototypeOf(obj,{x:20})
Obj.__prorp__ = {x:20}

2) Freeze the array

let a = [0]
Object.freeze(a) // Now the array cannot be modified a[0] = 1 // Failed a.push(2) // Failed

A frozen object is immutable. But it’s not always like this. The following shows that the frozen object is not a constant object (shallow freezing)

3) Shallow freezing

let obj = {
  internal: {}
}

Object.freeze(obj)
obj.internal.a = 'he'
console.log(obj.internal.a) // he

To make an object immutable, you need to recursively freeze every property of type object (deep freeze)

4) Deep Freeze

deepFreeze = (obj) => {
  var propNames = Object.getOwnPropertyNames(obj);
  propNames.forEach(function (name) {
    var prop = obj[name];
    if (typeof prop == 'object' && prop !== null) {
      deepFreeze(prop);
    }
  });
  Object.freeze(obj);
}


deepFreeze1 = (obj) => {
  var prop, propName
  Object.freeze(obj)
  for (propName in obj) {
    prop = obj[propName]
    if (!obj.hasOwnProperty(propName) || !(typeof prop === "object") || Object.isFrozen(prop)) {
      // Skip properties on the prototype chain and frozen objects.
      continue
    }
    deepFreeze1(prop)
  }
}

The use of deep freeze is usually when we need a property, but it is empty or does not exist at the beginning, then you just need to set some initial value

title: "Floor Sales",
value: "",
options: [],

The meaning of existence

If you have a huge array or Object and are sure that the data will not change, using Object.freeze() can significantly improve performance. Object.freeze() freezes the value, you can still replace the reference to the variable.

new vue({
  data: {
    // Vue will not bind getters and setters to objects in the list list: Object.freeze([
      { value: 1 },
      { value: 2 }
    ])
  },
  mounted () {
     // The interface will not respond this.list[0].value = 100;


     // The following two methods will respond to this.list = [
       { value: 100 },
       { value: 200 }
     ];
     this.list = Object.freeze([
       { value: 100 },
       { value: 200 }
     ]);
  }
})

The above is the detailed content of Object.freeze of JS Object constructor. For more information about JS Object.freeze, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • JavaScript knowledge: Constructors are also functions
  • Analysis of JavaScript constructor principle and implementation process
  • JavaScript class inheritance and instantiation methods
  • The difference between using new and not using instantiation objects in javascript
  • A brief discussion on javascript constructor and instantiation object
  • Detailed explanation of prototypes and prototype chains in JavaScript
  • Detailed explanation of the this pointing problem of JavaScript prototype objects
  • The relationship between JS constructor and instantiation and prototype introduction

<<:  Java+Tomcat environment deployment and installation process diagram

>>:  Ten useful and simple MySQL functions

Recommend

Vue3.0 adaptive operation of computers with different resolutions

First we need to install some dependencies npm i ...

Detailed explanation of Cgroup, the core principle of Docker

The powerful tool cgroup in the kernel can not on...

A brief introduction to MySQL functions

Table of contents 1. Mathematical functions 2. St...

What you need to know about filters in Vue

Table of contents Preface What is a filter How to...

A Preliminary Study on JSBridge in Javascript

Table of contents The origin of JSBridge The bidi...

Commonplace talk about MySQL event scheduler (must read)

Overview MySQL also has its own event scheduler, ...

Problems and solutions when replacing Oracle with MySQL

Table of contents Migration Tools Application tra...

Implementation of Nginx configuration of local image server

Table of contents 1. Introduction to Nginx 2. Ima...

CSS3 simple cutting carousel picture implementation code

Implementation ideas First, create a parent conta...

Several ways to change MySQL password

Preface: In the daily use of the database, it is ...

Details on using bimface in vue

Table of contents 1. Install Vue scaffolding 2. C...

Token verification login in Vue project (front-end part)

This article example shares the specific code of ...