gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:39:48 24 4
gpt4 key购买 nike

我有这个代码:

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
});
});
}

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

小引用:

“Arrow function expressions are a compact form of function expressions that omit the function keyword and have lexical scoping of this.” Basically the Arrow Function helps you retain a certain scope automatically. If you look at the outputted code from the compiler, it just creates a var _this = this; and it is used inside the function.

关于javascript - 如何在该类的另一个函数中使用在 Typescript 类中声明的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24861580/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com