简体   繁体   中英

How can I convert this to class-based Javascript?

I need help converting to class-based Javascript. Below is my code:

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);
};

This is what I have tried:

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)
    }

}

I am currently trying to see how class based Javascript works and to see if it is worth switching to.

Please, what could be wrong with this code?

The class class Foo is mostly ok. But, you shouldn't define class say . It has to be a member function within Foo

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)     }
}

Assuming that items is an array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM