javascript - 您可以在不更改对象构造函数的情况下向对象构造函数添加新的动态参数吗?
问题描述
我是 Javascript 新手,正在学习对象。我了解到您可以使用原型向对象添加新属性或方法。
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
现在我想知道是否也可以在不直接分配新属性或更改对象构造函数的情况下添加带有新参数的新属性。所以,它变成:
function Person(first, last, age, eyecolor, nationality) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = nationality;
}
解决方案
您可以通过将原始构造函数包装在新函数中来做到这一点,如下所示:
const originalPerson = Person;
Person = function(first, last, age, eyecolor, nationality) {
const instance = new originalPerson(first, last, age, eyecolor);
instance.nationality = nationality;
return instance;
};
现场示例:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
const originalPerson = Person;
Person = function(first, last, age, eyecolor, nationality) {
const instance = new originalPerson(first, last, age, eyecolor);
instance.nationality = nationality;
return instance;
};
const joe = new Person("Joe", "Bloggs", 42, "brown", "English");
console.log(joe.nationality);
你也可以通过继承来做到这一点:
const originalPerson = Person;
Person = class extends originalPerson {
constructor(first, last, age, eyecolor, nationality) {
super(first, last, age, eyecolor);
this.nationality = nationality;
}
};
现场示例:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
const originalPerson = Person;
Person = class extends originalPerson {
constructor(first, last, age, eyecolor, nationality) {
super(first, last, age, eyecolor);
this.nationality = nationality;
}
};
const joe = new Person("Joe", "Bloggs", 42, "brown", "English");
console.log(joe.nationality);
在这两种情况下我都重新分配了Person
,但你不必这样做,你可以使用ExtendedPerson
或类似的:
class ExtendedPerson extends Person {
constructor(first, last, age, eyecolor, nationality) {
super(first, last, age, eyecolor);
this.nationality = nationality;
}
}
...然后使用new ExtendedPerson(/*...*/)
.
现场示例:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
class ExtendedPerson extends Person {
constructor(first, last, age, eyecolor, nationality) {
super(first, last, age, eyecolor);
this.nationality = nationality;
}
}
const joe = new ExtendedPerson("Joe", "Bloggs", 42, "brown", "English");
console.log(joe.nationality);
推荐阅读
- python - 如何在python的多处理中访问更新的变量
- javascript - 使用javascript设置值的元素上的css转换
- discord - 如何在 discord.py 中制作货币系统?
- node.js - 连续编辑消息
- oracle - 将 Oracle 解码转换为 Postgres 案例表达式
- java - Java从编码数字中提取的有效方法
- c - stat st_mode 为/proc/1/task/1/fd/4 返回 0600
- javascript - React Hook 在页面加载时滚动到溢出 div 的底部
- r - 将数据框的列传递给内部函数
- postgresql - Mikro-orm 错误:用户“postgres”的密码验证失败