Skip to content

如何实现 const?

上次更新 2024年9月12日星期四 9:30:57 字数 0 字 时长 0 分钟

模拟行为

js
//   "use strict";
const obj = {};

function defineConst(name, value) {
  obj[name] = value;
  Object.defineProperty(obj, name, {
    // writable: false,
    configurable: false,
    set: function () {
      throw new TypeError("Assignment to constant variable.");
    },
  });
}
defineConst("name", "sss");
console.log(obj.name);
obj.name = "ssschange"; // Uncaught TypeError: Assignment to constant variable.
console.log(obj.name);
js
"use strict";
const obj = {};

function defineConst(name, value) {
  obj[name] = value;
  Object.defineProperty(obj, name, {
    writable: false,
    configurable: false,
    // set: function () {
    //   throw new TypeError("Assignment to constant variable.");
    // },
  });
}
defineConst("name", "sss");
console.log(obj.name);
obj.name = "ssschange"; // Uncaught TypeError: Cannot assign to read only property 'name' of object '#<Object>'
console.log(obj.name);