3 回答
TA贡献1862条经验 获得超6个赞
如果添加,将引发错误use strict:
'use strict';
const obj = {
deleteMe: "Some text",
dontDeleteMe: "Some other text"
};
Object.defineProperty(obj, 'dontDeleteMe', {
value: "Some text",
writable : true,
enumerable : true,
configurable : false
});
console.log(Object.keys(obj));
delete obj.deleteMe;
console.log(Object.keys(obj));
delete obj.dontDeleteMe;
console.log(Object.keys(obj));
带代理:
const obj = {
deleteMe: "Some text",
dontDeleteMe: "Some other text"
};
Object.defineProperty(obj, 'dontDeleteMe', {
value: "Some text",
writable : true,
enumerable : true,
configurable : false
});
const handler1 = {
deleteProperty(target, prop) {
delete target[prop];
if (target[prop]) {
throw new Error(`Invalid attempt to delete '${prop}' property`);
}
return true;
}
};
const proxyObj = new Proxy(obj, handler1);
console.log(Object.keys(proxyObj));
delete proxyObj.deleteMe;
console.log(Object.keys(proxyObj));
delete proxyObj.dontDeleteMe;
console.log(Object.keys(proxyObj));
TA贡献1847条经验 获得超11个赞
如果您不想使用“使用严格”(无论出于何种原因),这将是代理解决方案:
const obj = {
deleteMe: "Some text",
dontDeleteMe: "Some other text"
};
const deleteHandler = {
deleteProperty(target, prop) {
if (prop in target) {
const deleted = delete target[prop];
if (!deleted) {
console.error(`deletion not allowed: ${prop}`);
}
}
}
};
Object.defineProperty(obj, 'dontDeleteMe', {
value: "Some text",
writable: true,
enumerable: true,
configurable: false
});
const proxyObj = new Proxy(obj, deleteHandler);
console.log(Object.keys(proxyObj));
delete proxyObj.deleteMe;
console.log(Object.keys(proxyObj));
delete proxyObj.dontDeleteMe;
console.log(Object.keys(proxyObj));
添加回答
举报