Roy*_*y G 2 javascript ecmascript-6 es6-class
我尝试逐行调用类的方法,第二种方法是未定义的.
如何在ES6类中实现此模式?
await new Mail().attachments(files).send()
Run Code Online (Sandbox Code Playgroud)
在mail.js
export class Mail{
constructor(){
this.mail = {
*********
*********
};
}
attachments(files){
*********
*********
}
async send(){
try{
return await sendmail(this.mail, function(err) {
if(err){
return false
};
return true;
});
}catch(e){
throw e;
}
}
}
Run Code Online (Sandbox Code Playgroud)
你需要确保attachments结束,return this以便在它之后链接方法:
const sendmail = () => new Promise(res => setTimeout(res, 1000));
class Mail {
constructor() {
this.mail = 'mail';
}
attachments(files) {
console.log('adding attachments');
return this;
}
async send() {
console.log('sending...');
return sendmail(this.mail);
}
}
(async() => {
console.log('start');
const files = 'files';
await new Mail().attachments(files).send()
console.log('end');
})();Run Code Online (Sandbox Code Playgroud)
每当您想要定义要链接的方法时,请遵循相同的模式 - return this最后为了返回实例化的对象.