输出不正确,不确定如何修复

我必须有两个论点,name 和 dept,并创建了一个 name 和 dept 实例变量,默认为 name unknown 和部门 unknown,然后为它们创建 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,尽管我需要它默认为 name unknown of department unknown 除非另有设置。


蝴蝶不菲
浏览 128回答 3
3回答

largeQ

这是我如何放置它(并且它有效)编辑:既然选择了这个答案,我将在这里添加其他答案指出的好元素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());

慕侠2389804

一方面,您必须创建一个新实例,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 departmentconst faculty = new Faculty("John Smith", "Department XYZ");console.log(faculty.toString());//Without name and departmentconst faculty_default = new Faculty();console.log(faculty_default.toString());

一只甜甜圈

您也可以像这样使用默认参数: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());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript