在您的Persone 构造函数中,您可以使用您现在使用的相同符号将嵌套对象分配给它们在this(指新对象)上的属性:
function Persone() {
this.nome = "";
this.cognome = "";
this.sesso = "";
this.telefono = "";
this.indirizzo = {
via: "";
numero: "";
CAP: ""
};
this.nascita = {
mese: "";
giorno: "";
anno: "";
CAP: ""
};
this.codiceFiscale = function() {
// istruzioni per il calcolo
};
this.input = function(name, surname, sex, street, number, CAP1, day, month, year, CAP2) {
// istruzioni
};
}
当然,如果您愿意,可以将参数添加到Persone(用于nome 等)并在this 上创建属性时使用这些参数。
您可能会考虑将函数移至 new Persone 将分配给新实例的原型(除非它们对于不同的 Persone 实例需要不同),如下所示:
function Persone() {
this.nome = "";
this.cognome = "";
this.sesso = "";
this.telefono = "";
this.indirizzo = {
via: "";
numero: "";
CAP: ""
};
this.nascita = {
mese: "";
giorno: "";
anno: "";
CAP: ""
};
}
Persone.prototype.codiceFiscale = function() {
// istruzioni per il calcolo
};
Persone.prototype.input = function(name, surname, sex, street, number, CAP1, day, month, year, CAP2) {
// istruzioni
};
还值得一看新的class syntax,您现在可以将其与转译一起使用(或者越来越多地不使用):
class Persone {
constructor() {
this.nome = "";
this.cognome = "";
this.sesso = "";
this.telefono = "";
this.indirizzo = {
via: "";
numero: "";
CAP: ""
};
this.nascita = {
mese: "";
giorno: "";
anno: "";
CAP: ""
};
}
codiceFiscale() {
// istruzioni per il calcolo
}
input(name, surname, sex, street, number, CAP1, day, month, year, CAP2) {
// istruzioni
}
}
最后,如果你也想用构造函数创建那些嵌套对象,你只需这样做,然后在Persone 中使用构造函数:
class Indirizzo {
constructor() {
this.via = "";
this.numero = "";
this.CAP = "";
}
}
class Nascita {
constructor() {
this.mese = "";
this.giorno = "";
this.anno = "";
this.CAP = "";
}
}
class Persone {
constructor() {
this.nome = "";
this.cognome = "";
this.sesso = "";
this.telefono = "";
this.indirizzo = new Indirizzo();
this.nascita = new Nascita();
}
codiceFiscale() {
// istruzioni per il calcolo
}
input(name, surname, sex, street, number, CAP1, day, month, year, CAP2) {
// istruzioni
}
}