【问题标题】:Converting Calories Tracking application to ES6 Classes将卡路里跟踪应用程序转换为 ES6 类
【发布时间】: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


【解决方案1】:

你需要先初始化控制器:

class App {
    constructor(Item, UI) {
        this.item = new Item();
        this.UI = new UI();
    }

    init() {
        const items = this.item.getItems();

        this.UI.populateItemList(items)
    }
}

【讨论】:

  • 是的,这确实是问题所在。非常感谢。
  • 另外,例如,如果我要在转换为 ES6 类之前调用​​一个方法,我会使用ItemCtrl.logData() 在控制台中显示数据。但是,当我尝试从类中调用方法时遇到问题。我得到了他的:TypeError:Item.logData 不是函数
  • 除非在类上定义static 方法,否则不能直接从类中调用它。除了 static 之外的所有方法都是 instance 方法,这意味着您需要先创建该实例。在这里查看更多信息:stackoverflow.com/questions/11993077/…
猜你喜欢
  • 1970-01-01
  • 2020-05-27
  • 2017-09-10
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-01
  • 1970-01-01
相关资源
最近更新 更多