代码之家  ›  专栏  ›  技术社区  ›  Asad ullah

如何在角类型脚本中调用类中没有此对象的方法

  •  0
  • Asad ullah  · 技术社区  · 6 年前

    嗨,朋友们,我正在制作一个应用程序,通过gmail api列出用户的电子邮件。为此,我有一个方法,它列出来自用户帐户的线程,然后获取该线程中的消息。我的职能如下:

       public listThreads(opt_params){
        gapi.client.load('gmail', 'v1', function(){
    
            let request = gapi.client.gmail.users.threads.list({
                'userId': 'me',
                'q': opt_params
            });
            request.execute(function(response) {
    
                $.each(response.threads,  function() {
    
                   let thread_id = this.id;
    
                   this.getThread(thread_id, this.process_thread);
    // error appears on above line. which says "this.getThread is not a function" 
                });
            });
    });
        }
    

    错误是“this.getthread不是函数”。这是因为“this”现在指的是响应对象,不再指类成员但我需要调用getThread函数所以我需要知道是否有其他方法可以调用没有这个关键字的类函数?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Amit Chigadani    6 年前

    如果不使用 this

    相反你应该用脂肪 arrow operators (=>) 在代码中的三个位置 function ,以保留 是的。

    1. 参数 gapi.client.load()

       gapi.client.load('gmail', 'v1', () => {
                ......
       });
      
    2. 参数 request.execute()

      request.execute((response) => {
             ....
      })
      
    3. 每个$的参数

      $.each(response.threads, () => {
             let thread_id = this.id;
      
             this.getThread(thread_id, this.process_thread);
             // this should be accessible here
      });
      
        2
  •  0
  •   Sujay    6 年前

    因为环境, this 在回拨中丢失。使用typescript中的箭头函数保存上下文!

    request.execute().then((response)=> { // here you will have access to 'this' })