我正在尝试在一个对象中创建一个吸气剂,以返回适当类型的字段。
我得到它与此工作:
const getType = field => ({
email: "email",
telephone: "tel",
get type() {
return this[field] || "text";
}
});
我唯一的问题是,这是一个返回对象的函数。
我正在尝试通过基于传递的参数创建动态计算属性来采用稍微不同的方法。
我想做这样的事情:
const getType = {
email: "email",
telephone: "tel",
get [type]() {
return this[type] || "text";
}
};
但这会引发错误Error: type is not defined
。
我想在JavaScript中做些什么吗?
我知道我可以做类似的事情,
const fieldsMatrix = {
email: 'email',
telephone: 'tel',
}
['email', 'username'].map(field => <input type={fieldsMatrix[prop] || 'text'} />)
但这不是我要问的问题。
您可以使用Proxy
拦截所有尝试获取任何属性的尝试。
const getType = new Proxy({
email: "email",
telephone: "tel",
}, {
get(target, prop, receiver) {
return target[prop] || "text";
}
});
console.log(getType.email);
console.log(getType.somethingElse);
您也可以在对象上定义一个函数。
const types = {
email: "email",
telephone: "tel",
getType(type) {
return this[type] || "text";
}
};
console.log(types.getType('email'));
console.log(types.getType('somethingElse'));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句