我必须有两个参数,名称和部门,并创建一个名称和部门实例变量,默认为名称未知和部门未知,然后为它们创建 get 和 set 方法,但每次我运行这个它都会给我类名和部门未定义
最初我在类中没有它,而是将它作为一个直接的 const 函数,并且它正在工作,但是当我无法在另一个文件中正确引用它时,我被告知它们需要放入我尝试过的一个类,现在它没有提供我需要的输出。
class Faculty {
constructor(name, dept) {
this.name = "name unknown";
this.dept = "department unknown";
}
getName() {
return this.name;
}
getDept() {
return this.dept;
}
setName(name) {
this.name = name;
}
setDept(dept) {
this.dept = dept;
}
}
Faculty.toString = function () {
return this.name.concat(" of ").concat(this.dept);
}
//Faculty.name = "Testname";
//Faculty.dept = "Electronic Technology";
console.log(Faculty.toString());
当运行时,它给出了未定义的Faculty,即使当我尝试定义名称时,它仍然只是说Faculty,尽管我需要它默认为未知部门的名称未知,除非另有设置。
最佳答案
这就是我的说法(并且它有效)
编辑:既然选择了这个答案,我将在这里添加其他答案指出的好的元素
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());
关于javascript - 输出不正确,不确定如何修复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58272621/