如何在Typescript类中的另一个函数中使用在该类中声明的函数?

How can I use a function declared inside a Typescript class inside another function in that class?

本文关键字:函数 声明 另一个 Typescript      更新时间:2023-09-26

我有这样的代码:

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(),但我无法访问它。谁能告诉我怎么做呢

如果我们需要调用自己类的函数,我们总是必须使用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
      });
    });
  } 

查看更多关于箭头函数的详细信息:

    TypeScript箭头函数教程

小引用:

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