我需要在 ES6 中重构 IIFE。在 ES6 中,let 和 const 有 block 作用域,所以我真的需要 ES6 中的 IIFE 吗?这是ES5版本的代码:
var oojs = (function(oojs) {
var createToolbarItems = function(itemElements) {
var items = [];
[].forEach.call(itemElements,
function(el, index, array) {
var item = {
toggleActiveState: function() {
this.activated = !this.activated;
}
};
Object.defineProperties(item, {
el: {
value: el
},
enabled: {
get: function() {
return !this.el.classList.contains('disabled');
},
set: function(value) {
if (value) {
this.el.classList.remove('disabled');
} else {
this.el.classList.add('disabled');
}
}
},
activated: {
get: function() {
return this.el.classList.contains('active');
},
set: function(value) {
if (value) {
this.el.classList.add('active');
} else {
this.el.classList.remove('active');
}
}
}
});
items.push(item);
});
return items;
};
oojs.createToolbar = function(elementId) {
var element = document.getElementById(elementId);
var items = element.querySelectorAll('.toolbar-item');
return {
items: createToolbarItems(items)
}
};
return oojs;
}(oojs || {}));
在 ES6 中翻译这段代码的最佳方式是什么?我尝试了很多解决方案,但我错过了一些东西,并且收到错误:oojs is not Defined
。
也许我可以使用类来代替?正如您从代码中看到的,我正在以 OOP 方式编写 Toolbar API(我认为...)
感谢您的帮助
编辑:感谢 georg,我尝试使用类重构我的代码。这是新的 ES6 版本:
class Toolbar {
constructor(elementId) {
this.elementId = elementId;
}
get items() {
const element = document.getElementById(this.elementId);
return element.querySelectorAll(".toolbar-item");
}
createToolbarItems() {
return [...this.items].map(el => new ToolbarItem(el));
}
}
class ToolbarItem {
constructor(el) {
this.el = el;
}
get enabled() {
return !this.el.classList.contains('disabled');
}
set enabled(value) {
if (value) {
this.el.classList.remove('disabled');
} else {
this.el.classList.add('disabled');
}
}
get activated() {
return this.el.classList.contains('active');
}
set activated(value) {
if (value) {
this.el.classList.add('active');
} else {
this.el.classList.remove('active');
}
}
toggleActiveState() {
this.activated = !this.activated;
}
}
// const toolbar = new Toolbar('myToolbar');
// const toolbarItems = toolbar.createToolbarItems();
编辑:请检查编写此代码的方法是否正确,我对 ES6 还很陌生
再次感谢
最佳答案
您可以首先分解工具栏项代码(var item
及以下):
class ToolbarItem
{
constructor(element) {
....
}
}
现在,决定是否要将 enabled
和 activated
保留为属性,还是将它们重构为显式方法,例如 isEnabled
和 setEnabled
。在前一种情况下,
class ToolbarItem {
get enabled() {
...
}
set enabled(value) {
...
}
}
而普通方法可以这样定义:
class ToolbarItem {
isEnabled() {
...
}
setEnabled(value) {
...
}
}
解决此问题后,将项目初始化代码替换为 items.push(new ToolbarItem(el))
并进行测试。
希望这可以帮助您入门,祝您好运!
关于javascript - 在 ES6、OOP Javascript 编程中转换 ES5 IIFE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49010953/