NodeJS 访问方法启动在代理中调用console.log()时带有抛出错误

sxissh06  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(133)

我正在学习ES6代理,为此,我遵循javascript.info的指南,下面的示例,避免阅读,删除,添加新属性和列出属性,如果属性名称以下划线开头,例如_password

let user = {
  username: "john.doe",
  firstname: "John",
  lastname: "doe",
  email: "john.doe@example.com",
  _password: "******"
};

user = new Proxy(user, {
  get(target, property) {
    if (property.startsWith("_")) {
      throw new Error("Access denied");
    }

    return target[property];
  },

  set(target, property, value) {
    if (value.startsWith("_")) {
      throw new Error("Access denied");
    }

    target[property] = value;

    return true;
  },

  deleteProperty(target, property) {
    if (property.startsWith("_")) {
      throw new Error("Access denied");
    }

    delete target[property];

    return true;
  },

  ownKeys(target) {
    return Object.keys(target).filter(key => !key.startsWith("_"));
  }
});

const { username, firstname, lastname, email } = user;

console.log(username, firstname, lastname, email);
console.log(JSON.stringify(user, null, 2));
console.log(user);

console.log(JSON.stringify(user, null, 2));的调用显示了预期的输出,因为输出中省略了_password

{
    "username": "john.doe",
    "firstname": "John",
    "lastname": "doe",
    "email": "john.doe@example.com"
}

但是当调用console.log(user);时,我得到以下错误

/tmp/index.js:48
    if (property.startsWith("_")) {
                 ^

TypeError: property.startsWith is not a function

谢谢你的评论

ev7lccsx

ev7lccsx1#

当访问代理对象上的符号键控属性时(就像console.log在node.js中所做的那样),陷阱处理程序会将符号作为property参数传递,而不是属性名。当然,符号没有startsWith字符串方法。使用

if (typeof property == "string" && property.startsWith("_")) {

而是

相关问题