如何实现 const?
模拟行为
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);