实现一个const

# 实现一个const

/**
 * 实现一个const
 * 1.const指定的基本数据类型是不可变的
 * 2.指定的引用类型,代表的是指针,指针不可变
 * 3.思路:具体用Object.defineProperty来实现
 */
function myConst(obj, val) {
 window.obj = val;
 Object.defineProperty(window, obj, {
  enumerable: false,
  configurable: false,
  get() {
   return val;
  },
  set(data) {
   if (data !== val) {
    throw new TypeError('Assignment to constant variable.')
   } else {
    return val
   }
  },
 });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
上次更新: 2022/7/28 下午9:01:35