如何在__plugin
和add
内部css
内部return __plugin
返回return __plugin
。我可以使用更高阶的功能吗?一切都按预期工作,但我想知道并重构这段代码。
我不想每次只写一次const $ = (el) => {
let _plugin = {};
const element = document.querySelector.bind(document);
const css = (style) => {
Object.assign(element(el).style, style)
return _plugin;
}
const add = (c) => {
element(el).classList.add(c)
return _plugin;
}
_plugin = { add, css }
return _plugin
}
。
double miniVend::valueOfSnacks()
{
return //// I don't know how to get snacks price in here? I need to access snacks & getSnackPrice.
}
谢谢。
答案 0 :(得分:2)
您可以创建一个更高阶的函数来包装_plugin
对象中的每个函数,它将使您的所有函数都可链接。
const chainable = (obj) => {
for (const key in obj) {
const func = obj[key];
if (typeof func === 'function') {
obj[key] = function () {
const val = func.apply(this, arguments);
return val === undefined ? this : val;
};
}
}
return obj;
};
const $ = (el) => {
const element = document.querySelector(el);
const css = (style) => {
Object.assign(element.style, style);
};
const add = (c) => {
element.classList.add(c);
};
return chainable({ add, css });
};
/* Testing code */
$('#test')
.add('testClass')
.css({ 'background-color': 'black' });
.testClass { color: red; }
<div id="test">Testing</div>
答案 1 :(得分:1)
我假设您想要使用以下内容将对象附加到这些变量:
const $ = (el) => {
const element = document.querySelector.bind(document);
const css = (style) => {
Object.assign(element(el).style, style);
};
const add = (c) => {
element(el).classList.add(c);
};
return {add, css};
};
否则你只是返回未定义的对象,因为插件永远不会被操纵(或者依赖于多个条件)。
答案 2 :(得分:1)
基于评论..你可以像这样做一个小的重构:
const $ = (el) => {
const element = document.querySelector.bind(document);
const css = function(style) {
Object.assign(element(el).style, style)
return this;
}
const add = function(c) {
element(el).classList.add(c)
return this;
}
return { add, css };
};
如果你想摆脱使用插件并保持链接的能力,换掉常规功能的内部箭头功能。这允许您将作用域返回到$。