【发布时间】:2019-11-25 07:27:15
【问题描述】:
我设法从课程中重新创建了一个 MVC 卡路里跟踪器应用程序,我现在正尝试将其转换为 ES6 课程。
我在理解如何调用 Controller 内的 Module 中的方法以返回我需要的项目时有点卡住了。
class Item {
constructor() {
this.data = {
items: [{
name: 'Salad',
calories: 200,
id: 0
},
{
name: 'Eggs',
calories: 500,
id: 1
}],
totalCalories: 0,
currentItem: null
}
};
getItems() {
return this.data.items
};
logData = () => {
console.log(data.items);
};
}
class App {
constructor(Item, UI) {
this.Item = Item;
this.UI = UI;
}
init() {
const items = Item.getItems();
UI.populateItemList(items)
}
}
const application = new App(new Item(), new UI())
当我尝试在控制台中调用 Item.logData() 时,它给了我 TypeError: this.data is undefined。
我在网上查了一下,好像我声明的方法只针对构造函数。我将如何声明将在 Controller 或任何其他类中使用的方法,就像我在下面通过从构造函数中返回一个方法所做的那样?
我尝试转换的最初看起来像这样:
const ItemCtrl = (function () {
const Item = function (id, name, calories) {
this.name = name;
this.id = id;
this.calories = calories;
}
const data = {
items: StorageCtrl.getStorage(),
totalCalories: 0,
currentItem: null
}
return {
getItems: function () {
return data.items
},
logData: function () {
return data;
}
}
const App = (function (ItemCtrl, StorageCtrl, UICtrl) {
return {
init: function () {
const items = ItemCtrl.getItems();
UICtrl.populateItems(items);
}
}
})(ItemCtrl, StorageCtrl, UICtrl);
App.init();
【问题讨论】:
-
我是否遗漏了什么,或者您想在您的课程中拥有某种私有字段?
标签: javascript ecmascript-6 es6-class