[英]Can not call a method from inside another method in Javascript
Check my code below, I am just lost here why am I getting this error. 检查下面的代码,我只是在这里迷路,为什么会收到此错误。 Any suggestion please.
请提出任何建议。 Here I have made a class test and added two methods check and nextfn.
在这里,我进行了一个类测试,并添加了两个方法check和nextfn。 I am calling check from nextfn.
我正在打电话给nextfn。
var test=function(){}
test.prototype.check=function()
{
console.log("hello from checking");
}
test.prototype.nextFn=function(){
check();
console.log("Hello from nextfn");
}
Next 下一个
var t=new test();
t.nextfn();
The error is 错误是
Uncaught ReferenceError: check is not defined(…)
Now consider another scenario; 现在考虑另一种情况;
test.prototype.anotherFn=function()
{
var p=new Promise(function(){
this.check();
})
}
Now also getting same error; 现在也出现同样的错误;
Uncaught ReferenceError: check is not defined(…)
When calling 打电话时
var t=new test();
t.anotherFn();
The check
function is on the prototype of the test
object. check
功能位于test
对象的原型上。
When you invoke nextFn
like this: 当您像这样调用
nextFn
:
t.nextfn();
The ensuing scope will be bound to the t
instance of "type" test
. 随后的范围将绑定到“类型”
test
的t
实例。 Access within nextfn
to test
's prototype will be available via this
. 在
nextfn
中可以通过this
访问test
的原型。
So access check
using this
: 因此,使用
this
访问check
:
this.check();
This stuff can get surprisingly confusing. 这些东西令人惊讶地令人困惑。 A good reference is this book .
这本书是一个很好的参考。
==== ====
For your second scenerio, the problem is that you are trying to invoke this
from within a function that has it's own scope. 关于你的第二之情况,问题是,你试图调用
this
从具有它自己的范围内的功能。
Scope in JavaScript is generally not block scoped, but rather function scoped . JavaScript中的范围通常不是块范围的,而是函数范围的 。 There is a lot more to it, and I would recommend reading a tutorial on closures to get a more rounded description, but for now, try this instead:
还有更多功能,我建议阅读有关闭包的教程以获得更全面的描述,但是现在,尝试以下方法:
test.prototype.anotherFn=function()
{
var self = this; // save reference to current scope
var p=new Promise(function(){
self.check(); // use self rather than this
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.