如何在另一个类的构造函数中使用扩展方法?

问题描述 投票:0回答:1

我想在属于另一个类的构造函数中使用一个方法,但是我得到了错误:StorageCtrl.getItemsFromStorage不是一个函数

这是我的代码的一部分:

//Storage Controller
class StorageCtrl {
  constructor() {
    this.getItemsFromStorage();
  }

  getItemsFromStorage() {
    let items;
    if (localStorage.getItem('items') === null) {
      items = [];
    } else {
      items = JSON.parse(localStorage.getItem('items'));
    }
    return items;
  }

这是我要从中得到错误的类:

// Model 
class TaskModel extends StorageCtrl {
  constructor(id, name, calories) {
    super();
    this.id = id;
    this.name = name;
    this.calories = calories;

    // Data Structure / State
    this.data = {
      items: [
         {id: 0, name: 'Steack Dinner', calories: 1200},
         {id: 1, name: 'Cookie', calories: 400},
         {id: 2, name: 'Eggs', calories: 300}
           ],
      items: StorageCtrl.getItemsFromStorage(),  // The method that I`m trying to use
      currentItem: null,
      totalCalories: 0
    }
  }

非常感谢您的帮助或建议。

javascript class inheritance extension-methods
1个回答
0
投票

您可以通过两种方式访问​​类中的方法。

  1. 通过创建对象然后访问它。

例如,

class Sample{
  sayHello(){
    console.log('Hello');
  }
}

要从其他类访问sayHello,需要创建对象然后访问它。

class Sample1{
  constructor(){
    var obj = new Sample();
    obj.sayHello();
  }
}
  1. 通过静态方法。

我们将方法声明为静态的,>]

class Sample{
  static sayHello(){
    console.log('Hello');
  }
}

并访问sayHello这样的方法

class Sample1{
  constructor(){
    Sample.sayHello();
  }
}

为了更好地理解,请在类中探索静态变量。

这里参考很少

https://medium.com/@yyang0903/static-objects-static-methods-in-es6-1c026dbb8bb1

https://javascript.info/static-properties-methods

© www.soinside.com 2019 - 2024. All rights reserved.