尝试删除不允许的属性时引发错误

因此,我知道您可以通过将configurable对象的属性设置为来防止属性被删除false。但是,您从此delete操作中获得的唯一反馈是显示为true或false的布尔值。当删除不允许的属性时,有什么方法可以立即引发错误?


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));


慕哥9229398
浏览 167回答 3
3回答

阿波罗的战车

如果添加,将引发错误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));

回首忆惘然

如果您不想使用“使用严格”(无论出于何种原因),这将是代理解决方案: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));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript