Мне нужна помощь в преобразовании Javascript на основе классов. Ниже мой код:

function Foo(options) {
this.index = options.index;
this.name = options.name || 'foo';
var items = options.items;
var self = this;
function bar() {
    self.say();
}
items.forEach(function () {
    self.say();
});
for (var i = 0; i < items.length; i++) {
    bar();
}
}

Foo.prototype.say = function () {
    console.log(arguments);
};

Вот что я пробовал:

class Foo {
constructor(options) {
    this.index = options.index;
    this.name = options.name || 'foo';
    this.items = options.items

    this.items.forEach(() => {
        this.say()
    })
    for (var i = 0; i < items.length; i++) {
        this.bar();
    }
}
bar() {
    this.say();
}

}

class say extends Foo {
    constructor() {
       console.log(arguments)
    }

}

В настоящее время я пытаюсь увидеть, как работает Javascript на основе классов, и посмотреть, стоит ли переходить на него.

Пожалуйста, что может быть не так с этим кодом?

0
codebarz 19 Авг 2019 в 15:24

2 ответа

Лучший ответ
class Foo {
   constructor(options) {
      this.index = options.index
      this.name = options.name
      this.items = options.items

      var self = this

      this.items.forEach((e) => self.say(e))

      for(var i = 0; i < this.items.length; i ++) {
           this.bar(items[i])
      }
   }

   say(arg) { console.log(arg)  }
   bar(arg) { this.say(arg)     }
}

Предполагая, что элементы являются массивом

0
Narasimha Prasanna HN 19 Авг 2019 в 12:36

Класс class Foo в основном нормальный. Но вы не должны определять class say. Это должна быть функция-член в Foo

1
Aditya 19 Авг 2019 в 12:33