【发布时间】:2020-11-17 22:52:12
【问题描述】:
问题
所以基本上我正在尝试创建一个具有多个构造函数的类,以便它对用户更加友好。但是当我运行代码时,它会输出:
SyntaxError: /FileSystem.js: Duplicate constructor in the same class (13:2)
我知道Creating multiple constructor in ES6 可以回答这个问题,但我的代码对每个构造函数都有不同的参数:
Varun Sukheja 的代码
function Book() {
//just creates an empty book.
}
function Book(title, length, author) {
this.title = title;
this.Length = length;
this.author = author;
}
我的代码
class File
constructor(Name, Type, Data) {
this.Name = Name
this.Type = Type
this.Data = Data
}
constructor(FileName, Data) {
let FileNameSplit = FileName.split('.').pop();
this.Type = FileNameSplit[FileNameSplit.length - 1];
let NameSplit = FileNameSplit.pop()
this.Name = FileName;
this.Data = Data
}
}
如您所见,我的代码有 2 个构造函数(一个带有 constructor(Name, Type, Data) { ,另一个带有 constructor(FileName, Data) { )。所以你可以看到使用 Saransh Kataria 的代码是行不通的。
.
Saransh Kataria 的代码
constructor(title, length, author) {
if(!arguments.length) {
// empty book
}
else {
this.title = title;
this.Length = length;
this.author = author;
}
}
额外信息
IDE: 代码沙盒
浏览器: Chrome
完整代码:
class File {
/**
*
* @param {String} Name Name Of File
* @param {(String|Number)} Type File Type / Exstention
* @param {Array} Data
*/
constructor(Name, Type, Data) {
this.Name = Name
this.Type = Type
this.Data = Data
}
constructor(FileName, Data) {
let FileNameSplit = FileName.split('.').pop();
this.Type = FileNameSplit[FileNameSplit.length - 1];
let NameSplit = FileNameSplit.pop()
this.Name = FileName;
this.Data = Data
}
}
let Blob1 = new Blob([""])
console.log(Blob1)
【问题讨论】:
-
JavaScript 中类中的方法不能重载,也就是说不能有多个同名的函数。要实现这样的目标,您需要执行类似于您提供的“Saransh Kataria”代码的操作。我不知道你的意思是“所以你可以看到使用 Saransh Kataria 的代码,不会工作。”,因为它会,你只需要更改
if检查不同的长度
标签: javascript class es6-class