【发布时间】:2019-10-24 18:30:01
【问题描述】:
问题
我正在尝试创建两个类,其中一个是另一个的子类,并通过填充方法填充构造函数中的私有变量。但是,当使用fill方法填充父类私有变量时,这些变量会在初始化子类时消失。
class RequestFile {
constructor (args = {}) {
// this.to = args.to ? args.to : []
// this.files = args.files ? args.files : []
// this.body = args.body ? args.body : ''
}
fill ({to=[],files=[], subject='', body='', }) {
this.to = to
this.files = files
this.subject = subject
this.body = body
}
}
class Mail extends RequestFile {
constructor (args = {}) {
super(args)
this.fill(args)
}
fill ({cc='', draft=false, preview=true}) {
this.cc = cc
this.draft = draft
this.preview = preview
}
to() {
console.log(this.to)
}
}
let mail = new Mail({
to: [ 'name@gmail.com' ],
files: [ 1111 ],
subject: 'Sent from Node',
body: 'test body -- sent from node',
cc: [ 'anotherone@gmail.com', 'another@gmail.com' ],
draft: true,
preview: true
})
console.log(mail)
以上输出如下:
Mail {
cc:(2) [...],
draft: true ,
preview: true
}
取消注释 RequestFile 类中的代码会产生不同的结果:
class RequestFile {
constructor (args = {}) {
this.to = args.to ? args.to : []
this.files = args.files ? args.files : []
this.body = args.body ? args.body : ''
}
fill ({to=[],files=[], subject='', body='', }) {
this.to = to
this.files = files
this.subject = subject
this.body = body
}
}
Mail {
to:(1) [...],
files:(1) [...],
body: "test body -- sent from node" ,
cc:(2) [...],
draft: true ,
preview: true
}
理想情况下,我想依靠 fill 方法来填充类变量,我只是对为什么它在子类(Mail)中工作但在父类(RequestFile)中不起作用感到困惑
【问题讨论】:
-
子类
.fill()必须显式调用父类版本。解构会变得很棘手,但你不必那样写。 -
啊,我明白了,谢谢你的回复。我认为父类填充方法会自动调用,因为它是由构造函数调用的。
-
您也必须显式调用父构造函数(通过
super())。
标签: javascript inheritance constructor