从同一个类中的另一个方法调用一个方法 [英] Calling a method from another method in the same class
本文介绍了从同一个类中的另一个方法调用一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么会出现错误:未捕获的TypeError:self.myTest不是函数"?如何在javascript类的另一个方法中调用一个方法?
Why am I getting the error: "Uncaught TypeError: self.myTest is not a function"? How do I call a method from within another method in a javascript class?
class MyClass {
myTest() {
console.log('it works');
}
runMyTest() {
self.myTest();
}
}
var myClass = new MyClass();
myClass.runMyTest();
推荐答案
您需要使用this
关键字而不是self
.
You need to use the this
keyword instead of self
.
runMyTest() {
this.myTest();
}
旁注
如果要嵌套标准函数符号,则this
不受词法约束(将是未定义的).要解决此问题,请使用箭头功能(首选),.bind
,或在功能外部局部定义this
.
If you are nesting standard functions notation then this
is not lexically bound (will be undefined). To get around this, use Arrow Functions (preferred), .bind
, or locally define this
outside of the function.
class Test {
constructor() {
this.number = 3;
}
test() {
function getFirstThis() {
return this;
}
const getSecondThis = () => {
return this;
};
const getThirdThis = getFirstThis.bind(this);
const $this = this;
function getFourthThis() {
return $this;
}
// undefined
console.log(getFirstThis());
// All return "this" context, containing the number property
console.log(this);
console.log(getSecondThis());
console.log(getThirdThis());
console.log(getFourthThis());
}
}
new Test().test();
这篇关于从同一个类中的另一个方法调用一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文