[英]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? 因此,它是否要求我们允许某人创建实例而不使用
new
关键字?
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? 如何允许某人使用此功能创建实例而不使用
new
关键字?
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: 实际上,正如@Paulpro在其评论中解释的那样,这确实解决了挑战:
function makeClass( ...props ) {
return function ( ...args ) {
props.forEach( (prop, i) => this[prop] = args[i] )
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.