为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕哥9229398 2021-04-08 14:15:22
因此,我知道您可以通过将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));
查看完整描述

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


查看完整回答
反对 回复 2021-04-22
?
回首忆惘然

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


查看完整回答
反对 回复 2021-04-22
  • 3 回答
  • 0 关注
  • 164 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信