【问题标题】:How can I use a function declared inside a Typescript class inside another function in that class?如何在该类的另一个函数中使用在 Typescript 类中声明的函数?
【发布时间】:2014-07-21 09:21:21
【问题描述】:

我有这个代码:

class ExamPage {

  tabClear() {
    page.clear(this.examName);
    page.clear(this.examVersionId);
  }

  createNew() {
    describe('Create new' , function() {
      it('Clear input boxes', function() {
        tabClear(); // <<< not recognized 
      });
    });
  }

}

谁能给我建议。我想调用函数 tabClear() 但我无法访问它。有人能告诉我怎么做吗

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    如果我们需要调用我们自己的类的函数,我们总是必须使用 this

    class ExamPage {
    
      tabClear() {
        page.clear(this.examName);
        page.clear(this.examVersionId);
      }
    
      createNew() {
        describe('Create new' , function() { 
          it('Clear input boxes', function() {
            this.tabClear(); // HERE the this.tabClear() is the answer
          });
        });
      }    
    }
    

    但实际上,我们也应该使用箭头函数表示法,这样可以保持 this 的正确范围:

    createNew() {
        // the function () is replaced with arrow function
        describe('Create new' , () => {
          it('Clear input boxes', () => {
            this.tabClear(); // HERE the this.tabClear() is the answer
          });
        });
      } 
    

    在此处查看有关箭头功能的更多详细信息:

    小引用:

    “箭头函数表达式是函数表达式的一种紧凑形式,它省略了 function 关键字并具有 this 的词法范围。” 基本上,箭头函数可以帮助您自动保留一定的范围。如果您查看编译器的输出代码,它只会创建一个 var _this = this;并且在函数内部使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多