KOU*_*DAL 2 javascript oop methods prototype class
检查下面的代码,我只是在这里迷路,为什么会收到此错误。请提出任何建议。在这里,我进行了一个类测试,并添加了两个方法check和nextfn。我正在打电话给nextfn。
var test=function(){}
test.prototype.check=function()
{
console.log("hello from checking");
}
test.prototype.nextFn=function(){
check();
console.log("Hello from nextfn");
}
Run Code Online (Sandbox Code Playgroud)
下一个
var t=new test();
t.nextfn();
Run Code Online (Sandbox Code Playgroud)
错误是
Uncaught ReferenceError: check is not defined(…)
Run Code Online (Sandbox Code Playgroud)
现在考虑另一种情况;
test.prototype.anotherFn=function()
{
var p=new Promise(function(){
this.check();
})
}
Run Code Online (Sandbox Code Playgroud)
现在也出现同样的错误;
Uncaught ReferenceError: check is not defined(…)
Run Code Online (Sandbox Code Playgroud)
打电话时
var t=new test();
t.anotherFn();
Run Code Online (Sandbox Code Playgroud)
该check函数位于对象的原型上test。
当您这样调用时nextFn:
t.nextfn();
Run Code Online (Sandbox Code Playgroud)
随后的作用域将绑定到t“ type” 的实例test。内访问nextfn到test的原型将通过可用this。
所以访问check使用this:
this.check();
Run Code Online (Sandbox Code Playgroud)
这些东西令人惊讶地令人困惑。这本书是一个很好的参考。
====
对于第二个场景,问题是您试图this从具有自己作用域的函数中调用。
JavaScript中的范围通常不是块范围的,而是函数范围的。还有更多功能,我建议阅读有关闭包的教程以获得更全面的描述,但是现在,尝试以下方法:
test.prototype.anotherFn=function()
{
var self = this; // save reference to current scope
var p=new Promise(function(){
self.check(); // use self rather than this
})
}
Run Code Online (Sandbox Code Playgroud)