我不明白this problem想要我们做什么。
说明说:
我真的不喜欢写这样的课程:
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;
}
请赋予我创建类似此类的权力:
const Animal = makeClass("name","species","age","health","weight","color")
据我了解,上面的第一个代码块是一个构造函数,在这里,如果您想创建一个实例,则可以执行以下操作:
const Animal = new Animal("name","species","age","health","weight","color")
是否要求我们允许某人使用new
关键字创建实例而?
它为我们提供了以下代码:
function makeClass(...properties) {
}
如何允许某人使用此功能创建实例而不使用new
关键字?
答案 0 :(得分:0)
尝试一下:
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"
}
*/
答案 1 :(得分:0)
实际上,正如@Paulpro在其评论中解释的那样,这确实解决了挑战:
function makeClass( ...props ) {
return function ( ...args ) {
props.forEach( (prop, i) => this[prop] = args[i] )
};
}