Javascript OOP class 对象继承
Javascript OOP class object inheritance
下面的Javascript代码输出:
员工{#name: "sheila", #gender: "女", #manager: 员工, #job: 职位}
如何修复它以便输出:
员工{#name: “sheila”, #gender: “女”, #manager: “pierre”, #job: “软件工程师”}
不确定是否有吊装问题。
我应该修改哪几行,以便#manager 是“pierre”而#job 是“软件工程师”?
class Person{
#name;
#gender;
constructor(name, gender) {
this.#name = name;
this.#gender = gender;
};
setName(name) {
this.#name = name;
};
getName() {
return this.#name;
};
setGender(gender) {
this.#gender = gender;
}
getGender() {
return this.#gender;
};
}
class Employee extends Person{
#manager;
#job;
constructor(name, gender, manager, job) {
super(name, gender);
this.#manager = manager;
this.#job = job;
};
setManager(manager) {
this.#manager = manager;
}
getManager() {
return this.#manager;
}
setJob(job) {
this.#job = job;
}
getJob() {
return this.#job;
}
}
class Job {
#title;
constructor(title) {
this.#title = title;
};
}
const softwareEngineer = new Job("software engineer");
const keith = new Employee("keith", "male");
const pierre = new Employee("pierre", "male");
const sheila = new Employee("sheila", "female", keith, softwareEngineer);
sheila.setManager(pierre);
console.log(sheila);
问题是您打印了对象的类型而不是值。 Job 和 Manager 需要一个 toString 函数来打印值而不是类型,请参阅 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
下面的Javascript代码输出: 员工{#name: "sheila", #gender: "女", #manager: 员工, #job: 职位}
如何修复它以便输出: 员工{#name: “sheila”, #gender: “女”, #manager: “pierre”, #job: “软件工程师”}
不确定是否有吊装问题。 我应该修改哪几行,以便#manager 是“pierre”而#job 是“软件工程师”?
class Person{
#name;
#gender;
constructor(name, gender) {
this.#name = name;
this.#gender = gender;
};
setName(name) {
this.#name = name;
};
getName() {
return this.#name;
};
setGender(gender) {
this.#gender = gender;
}
getGender() {
return this.#gender;
};
}
class Employee extends Person{
#manager;
#job;
constructor(name, gender, manager, job) {
super(name, gender);
this.#manager = manager;
this.#job = job;
};
setManager(manager) {
this.#manager = manager;
}
getManager() {
return this.#manager;
}
setJob(job) {
this.#job = job;
}
getJob() {
return this.#job;
}
}
class Job {
#title;
constructor(title) {
this.#title = title;
};
}
const softwareEngineer = new Job("software engineer");
const keith = new Employee("keith", "male");
const pierre = new Employee("pierre", "male");
const sheila = new Employee("sheila", "female", keith, softwareEngineer);
sheila.setManager(pierre);
console.log(sheila);
问题是您打印了对象的类型而不是值。 Job 和 Manager 需要一个 toString 函数来打印值而不是类型,请参阅 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString