代码之家  ›  专栏  ›  技术社区  ›  Roy G

如何对类方法进行多次内联(链式调用)JavaScript es6调用

  •  2
  • Roy G  · 技术社区  · 8 年前

    我尝试逐个内联调用类的方法,但第二个方法未定义。

    如何在ES6类中实现此模式?

    await new Mail().attachments(files).send()
    

    邮件.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;
            }
    
    
        }
    }
    
    1 回复  |  直到 8 年前
        1
  •  5
  •   CertainPerformance    8 年前

    你要确定 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');
    })();

    每当您想定义一个要链接的方法时,都要遵循相同的模式- 把这个还给我 以返回实例化的对象。