Reprint: How to achieve a const in ES5 environment

This article is reproduced from:
how to achieve a const in ES5 environment
https://juejin.im/post/5ce3b2d451882533287a767f
const realization of the principle
Since there is no concept of block ES5 environment, it is impossible to achieve hundred percent const, can only be mounted to a the next object is global or window, or is a custom object to the container when

      var __const = function __const (data, value) {
        window.data = value // 把要定义的data挂载到window下,并赋值value
        Object.defineProperty(window, data, { // 利用Object.defineProperty的能力劫持当前对象,并修改其属性描述符
          enumerable: false,
          configurable: false,
          get: function () {
            return value
          },
          set: function (data) {
            if (data !== value) { // 当要对当前属性进行赋值时,则抛出错误!
              throw new TypeError('Assignment to constant variable.')
            } else {
              return value
            }
          }
        })
      }
      __const('a', 10)
      console.log(a)
      delete a
      console.log(a)
      for (let item in window) { // 因为const定义的属性在global下也是不存在的,所以用到了enumerable: false来模拟这一功能
        if (item === 'a') { // 因为不可枚举,所以不执行
          console.log(window[item])
        }
      }
      a = 20 // 报错

Vue core of the current two-way binding realize the idea is to use Object.defineProperty to get hijacking with set, listening to user attributes and call the specific circumstances of the assignment, in order to achieve the two-way binding ~~
attribute descriptors:
objects in the current two attribute descriptor:

Data Descriptor: a property value
access descriptor: a getter and setter properties described function

Function Descriptor:
Data descriptors access descriptor Jieke Review:

configurable: this attribute descriptor elements whether the object can be changed, whether to delete
enumerable: current object element is enumerable

Only data descriptor can be modified:

value: The current value of the element to be
writable: whether the current value of the element to be modified

You may be modified only access descriptor:

get: reading operation element attribute values
set: modify operation of element attribute values

Descriptor may have keys simultaneously:

configurable	enumerable	value	writable	get	set

Data Descriptor Yes Yes Yes Yes No No
access descriptor Yes Yes No No Yes Yes

Guess you like

Origin www.cnblogs.com/smart-girl/p/12656336.html