Application in vue: If you have a huge array or Object and are sure that the data will not be modified, you can use Object.freeze() method to freeze the data, so that Vue will not convert getter and setter of the object, thus greatly improving performance.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <span v-for="item in list">{{item.name}}</span> </div> <script type="text/javascript" src="../../../js/lib/vue-2.5.21.js"></script> <script> 'use strict' new Vue({ el: '#app', data() { return { list: Object.freeze([{ name: '1' }, { name: '2' }]) } }, mounted() { this.list[0].name = '3' // It will not take effect. // If you change the reference to this.list directly, it will take effect. this.list = [{name: 4}] // or this.list = Object.freeze([{name: 4}]) } }) </script> </body> </html>
Object.freeze()
Object.freeze() method can freeze an object. A frozen object can no longer be modified; a frozen object cannot add new attributes to the object, delete existing attributes, modify the enumerability, configurability, writability of existing attributes of the object, and cannot modify the value of existing attributes. In addition, the prototype of an object can not be modified after it is frozen. freeze() returns the same object as the parameter passed in.
var obj = { prop: function() {}, foo: 'bar' } // Normally we can modify attribute values or delete attributes obj.foo = 'bas' obj.lumpy = 'woof' delete obj.prop //When obj is frozen var o = Object.freeze(obj) o === obj // true // Now any change will fail. obj.foo = '23' // Quietly will not do anything, in strict mode will throw the error TypeErrors // Attempt to change properties through Object.defineProperty // Both of the following statements throw TypeError. Object.defineProperty(obj, 'ohai', { value: 17 }); Object.defineProperty(obj, 'foo', { value: 'eit' }); // Nor can we change the prototype // Both of the following statements throw TypeError. Object.setPrototypeOf(obj, { x: 20 }) obj.__proto__ = { x: 20 } //The same array will be frozen let a = [0]; Object.freeze(a); // Now the array cannot be modified. a[0]=1; // fails silently a.push(2); // fails silently // In strict mode such attempts will throw TypeErrors function fail() { "use strict" a[0] = 1; a.push(2); } fail(); //The object of freezing is shallow freezing