我正在学习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
谢谢你的评论
1条答案
按热度按时间ev7lccsx1#
当访问代理对象上的符号键控属性时(就像
console.log
在node.js中所做的那样),陷阱处理程序会将符号作为property
参数传递,而不是属性名。当然,符号没有startsWith
字符串方法。使用而是