1

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.

4
  • what is the problem Commented May 3, 2020 at 7:42
  • Client requirement and for easy of understanding as current library is too big and complex. Commented May 3, 2020 at 7:43
  • you would need to rewrite them manually. Even if there are tools available it's not recommended to use as there will be problems for complex implementation and logic. Commented May 3, 2020 at 7:53
  • Which tool is available? I would like to try once Commented May 4, 2020 at 17:34

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
This is what OP is posted, what is this answer trying to do? he want to convert what you have repeated here to a class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.