【发布时间】:2019-10-28 18:48:04
【问题描述】:
所以这就是他们要求我做的事情: 1) 使用以下条件创建一个名为 Person 的类。 属性:姓名、年龄、DNI、性别(M 为男性,F 为女性)、体重和身高。 除 DNI 外,每个属性都将根据其类型(数字为 0,字符串为空字符串等)具有默认值。性别默认为男性。
2) 创建以下构造函数: • 具有默认值的构造函数。 • 以姓名、年龄和性别为参数的构造函数(默认为其他值)。 • 将所有属性作为参数接收的构造函数。
我需要知道执行此操作的正确方法,以便能够创建具有不同值的类的 3 个对象。
class Person {
constructor(name, age, sex, dni, weight, height){
this.name = '';
this.age = 0;
this.sex = 'M';
this.dni = createDni();
this.weight = 0;
this.height = 0;
}
static Person1(name, age, sex){
return new Person(name,age,sex);
}
static Person2(name, age, sex, dni, weight, height){
return new Person(name, age, sex, dni, weight, height);
}
}
var Person1 = new Person(){
this.name = 'Manuel'
this.age = 25;
this.sex = 'M';
this.height = 1,75;
this.weight = 90;
}
我应该能够将不同的值传递给从“类”创建的 3 个不同的对象。
【问题讨论】:
-
这个任务是不可能的。一个类只能有一个
constructor。 -
你确定这是一个 Javascript 而不是 Java 作业吗?
-
他们给了我这个练习来获得一份工作的面试,这些文件都被称为“测试 JS”,所以我不得不假设它是 Javascript。当类似的事情可以更简单地完成时,这种复杂的答案不可能是他们想要的。
标签: javascript class constructor