本来在看vue的数据劫持,然后突发奇想,能不能用数据劫持来实现const的禁止重复赋值功能呢,于是开撸,代码很简短
function Gconst(e, v, data) {
if (!data) data = window;
var val = data[e], c = 1;
Object.defineProperty(data, e, {
enumerable: true, // 可枚举
configurable: false, // 不能再define
get: function () {
return val;
},
set: function (newVal) {
if (c > 1)throw new Error('const不能重复赋值')
c++
val = newVal;
}
});
data[e] = v
return data[e]
}
输入浏览器验证:
Gconst('g',1)
当变量为对象时,其内部属性可变:
