gpt4 book ai didi

javascript - 一个类中有多个构造函数。 JavaScript

转载 作者:行者123 更新时间:2023-12-01 00:30:24 24 4
gpt4 key购买 nike

这就是他们要求我做的事情: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 个不同对象。

最佳答案

JavaScript 的 class 语法创建一个构造函数和一个关联的原型(prototype)对象。 JavaScript 中没有内置的函数重载,包括构造函数。在 JavaScript 中进行“重载”的唯一方法是在一个函数本身的代码中处理它。

就您而言,您有多种选择,但最简单的可能是对所有参数使用默认参数值:

constructor(name = '', age = 0, sex = 'M', dni = createDni(), weight = 0, height = 0) {
this.name = name;
this.age = age;
this.sex = sex;
this.dni = dni;
this.weight = weight;
this.height = height;
}

别担心,只有在调用构造函数时没有为 dni 提供参数(或者提供的值为 undefined)。

这样做的一个优点是调用者可以为任何参数、所有参数或中间的任何参数提供参数,而不仅仅是 0、3 和 6。

实例:

function createDni() {
console.log("createDni was called");
return 42;
}
class Person {
constructor(name = '', age = 0, sex = 'M', dni = createDni(), weight = 0, height = 0) {
this.name = name;
this.age = age;
this.sex = sex;
this.dni = dni;
this.weight = weight;
this.height = height;
}
}
console.log("No arguments:");
console.log(JSON.stringify(new Person()));
console.log("Three arguments:");
console.log(JSON.stringify(new Person("Joe Bloggs", 42, "M")));
console.log("Six arguments:");
console.log(JSON.stringify(new Person("Joe Bloggs", 42, "M", 67, 182, 6)));
.as-console-wrapper {
max-height: 100% important;
}

如果您确实只想允许无参数、三个参数或六个参数,则可以使用剩余参数或 arguments 对象。使用参数将如下所示:

constructor(name = '', age = 0, sex = 'M', dni = createDni(), weight = 0, height = 0) {
const alen = arguments.length;
if (alen !== 0 && alen !== 3 && alen !== 6) {
throw new Error("0, 3, or 6 arguments are required");
}
this.name = name;
this.age = age;
this.sex = sex;
this.dni = dni;
this.weight = weight;
this.height = height;
}

使用剩余参数如下所示,请注意,您会丢失命名参数:

constructor(...args) {
const alen = args.length;
if (alen !== 0 && alen !== 3 && alen !== 6) {
throw new Error("0, 3, or 6 arguments are required");
}
[
this.name = "",
this.age = 0,
this.sex = "M",
this.dni = createDni(),
this.weight = 0,
this.height = 0
] = args;
}

...这里,再次强调,createDni 仅在需要时调用。

关于javascript - 一个类中有多个构造函数。 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58596741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com