javascript - 用于缓存 css 属性名称的通用函数
问题描述
我创建了这个对象来根据浏览器获取 css 属性名称。例如,js.transition 将根据需要返回“webkitTransition”或“transition”。所有值都被缓存,即。第一次引用将在 testElementStyle 对象中查找值,重复引用将返回缓存的值。
const js = {
get testElementStyle() {
delete this.testElementStyle;
return this.testElementStyle = document.createElement('div').style;
},
get transition() {
delete this.transition;
return this.transition = "transition" in this.testElementStyle ? "transition" : "webkitTransition"
},
get transform() {
delete this.transform;
return this.transform = "transform" in this.testElementStyle ? "transform" : "webkitTransform"
},
get userSelect() {
delete this.userSelect
return this.userSelect = "userSelect" in this.testElementStyle ? "userSelect" : "webkitUserSelect" }
}
如您所见,每个属性的缓存代码都是重复的。理想情况下,我想创建一个接受道具名称并完成其余工作的通用函数。
例如
const cache = prop => alt => {
delete this[prop];
return this[prop] = prop in this.testElementStyle ? prop : alt;
}
...这当然行不通,我有点卡住了,请帮忙!
这是我在阅读您的评论之前所做的。有了你的建议,我现在可以把它提升到一个新的水平。感谢大家!
const testElementStyle = document.createElement('div').style;
function cache(prop, alt) {
delete this[prop];
return this[prop] = prop in testElementStyle ? prop : alt;
}
const js = {
get transition() { return cache.call(this, "transition", "webkitTransition") },
get transform() { return cache.call(this, "transform", "webkitTransform") },
get userSelect() { return cache.call(this, "userSelect", "webkitUserSelect") },
}
const css = {
get transform() { return cache.call(this, "transform", "-webkit-transform") },
}
解决方案
你有两个选择:
使用函数并传入字符串
使用
Proxy
(ES2015+)
由于CertainPerformance 已经覆盖了代理,因此您可以使用函数来执行此操作:
const js = {
get testElementStyle() {
return this.testElementStyle = document.createElement('div').style;
},
get(name) {
return this[name] = name in this.testElementStyle ? name : "webkit" + name.substring(0, 1).toUpperCase() + name.substring(1);
}
};
用法:
js.testElementStyle(); // It's unclear to me why you make this setup call necessary
const transform = js.get("transform");
推荐阅读
- swift - 尽管从开发人员文档中复制,但设置不起作用
- java - 如何在 gradle 5.0.0 中将 bootRepackage 任务转换为 kotlin DSL?
- c++ - 将方法作为参数传递给另一个方法,该方法本身将传递的方法传递给 std 线程
- mongodb - 如果该字段在集合中不存在,则检查并更新
- python - Django Rest Framework 的 @api_view 装饰器的使用和神秘的 bug
- protractor - 使用量角器在 Shadow-root 中定位元素
- google-chrome - Chrome 多功能框查询字符串中断,替换我的“?” 使用“%3F”
- sql - 在postgresql中,只有当“deleted”为假时,如何才能使“name”唯一?
- java - Spring Boot 伪装异常
- java - 无法使用 Java Spring 连接到 MySQL