简体   繁体   中英

Make Class - Javascript CodeWars Challenge

I don't understand what this problem wants us to do.

Instructions say:


I don't really like writing classes like this:

function Animal(name,species,age,health,weight,color) {
  this.name = name;
  this.species = species;
  this.age = age;
  this.health = health;
  this.weight = weight;
  this.color = color;
}

Give me the power to create a similar class like this:

const Animal = makeClass("name","species","age","health","weight","color") 

As far as I understand, the first code block above is a Constructor function, where, if you wanted to create an instance, you could then do something like:

const Animal = new Animal("name","species","age","health","weight","color")

So it's asking for us to allow someone to create an instance without using the new keyword?

It gives us this code to start with:

function makeClass(...properties) {

}

How can I allow someone to create an instance with this function without using the new keyword?

Try this:

function makeClass(){
  let newClass = Object.create(null);

  for(let property of arguments){
    newClass[property] = property;
  }
  return newClass;
}

console.log(makeClass("name","species","age","health","weight","color"));

/*
Returns:
{
name:   "name"
species:"species"
age:    "age"
health: "health"
weight: "weight"
color:  "color"
}
*/

In fact, as @Paulpro explained in their comment, this does solve the challenge:

function makeClass( ...props ) { 
  return function ( ...args ) { 
  props.forEach( (prop, i) => this[prop] = args[i] ) 
  }; 
}

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