3 回答
TA贡献2039条经验 获得超7个赞
这是我如何放置它(并且它有效)
编辑:既然选择了这个答案,我将在这里添加其他答案指出的好元素
const DEFAULT_NAME = "name unknown";
const DEFAULT_DEPT = "department unknown";
class Faculty {
constructor(name = DEFAULT_NAME, dept DEFAULT_DEPT) {
this.name = name;
this.dept = dept;
}
getName() {
return this.name;
}
getDept() {
return this.dept;
}
setName(name) {
this.name = name;
}
setDept(dept) {
this.dept = dept;
}
toString() {
return `${this.name} of ${this.dept}`;
}
}
const f = new Faculty("Faculty", "Department");
console.log(f.toString());
TA贡献1719条经验 获得超6个赞
一方面,您必须创建一个新实例,Faculty才能调用其类方法之一。
其次,不需要toString在类外声明方法;它可以像其他人一样被包括在内。
第三,我认为可以通过使用模板文字来简化/澄清方法本身。
const DEFAULT_NAME = "name_unknown";
const DEFAULT_DEPARTMENT = "department_unknown";
class Faculty {
constructor(name, dept) {
this.name = name || DEFAULT_NAME;
this.dept = dept || DEFAULT_DEPARTMENT;
}
getName() {
return this.name;
}
getDept() {
return this.dept;
}
setName(name) {
this.name = name;
}
setDept(dept) {
this.dept = dept;
}
toString() {
return `${this.name} of ${this.dept}`
}
}
//With name and department
const faculty = new Faculty("John Smith", "Department XYZ");
console.log(faculty.toString());
//Without name and department
const faculty_default = new Faculty();
console.log(faculty_default.toString());
TA贡献1836条经验 获得超5个赞
您也可以像这样使用默认参数:
class Faculty {
constructor(name = 'name unknown', dept = 'department unknown') {
this.name = name;
this.dept = dept;
}
getName() {
return this.name;
}
getDept() {
return this.dept;
}
setName(name) {
this.name = name;
}
setDept(dept) {
this.dept = dept;
}
toString() {
return `${this.name} of ${this.dept}`;
}
}
const f = new Faculty('Alex', 'Maths');
console.log(f.toString());
添加回答
举报