Jigar Parekh
Jigar Parekh

Reputation: 625

Javascript convert prototype based library to object oriented class

I have some old javascript library, which is written in prototype structure. I want to convert it into latest Class base structure.

I have search on google but cant find any available tool for it. Or is there any other technique to convert prototype to Class.

Prototype sructure Example:

function Animal (name, energy) {
  let animal = Object.create(Animal.prototype)
  animal.name = name
  animal.energy = energy

  return animal
}

Animal.prototype.eat = function (amount) {
  console.log(`${this.name} is eating.`)
  this.energy += amount
}

Animal.prototype.sleep = function (length) {
  console.log(`${this.name} is sleeping.`)
  this.energy += length
}

I want to convert it into

class Animal {
  constructor(name, energy) {
    this.name = name
    this.energy = energy
  }
  eat(amount) {
    console.log(`${this.name} is eating.`)
    this.energy += amount
  }
  sleep(length) {
    console.log(`${this.name} is sleeping.`)
    this.energy += length
  }

}

I would like to keep comments as it is in the file. and there are some variables also which needs to be converted.

Upvotes: 1

Views: 963

Answers (1)

Aissaoui Ahmed
Aissaoui Ahmed

Reputation: 257

Try Lebab the revers of Babel great framework Transforms JavaScript

The transform of your code looks like this:

function Animal (name, energy) {
  let animal = Object.create(Animal.prototype)
  animal.name = name
  animal.energy = energy

  return animal
}

Animal.prototype.eat = function (amount) {
  console.log(`${this.name} is eating.`)
  this.energy += amount
}

Animal.prototype.sleep = function (length) {
  console.log(`${this.name} is sleeping.`)
  this.energy += length
}

Note: some Transforms are unsafe

Upvotes: 2

Related Questions