gpt4 book ai didi

javascript - 无法从Javascript中的另一个方法内部调用方法

转载 作者:行者123 更新时间:2023-11-29 16:06:01 25 4
gpt4 key购买 nike

检查下面的代码,我迷路了,为什么会出现此错误。请有任何建议。这里我做了一个类测试,添加了两个方法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");
}

下一步

var t=new test();
t.nextfn();

错误是

Uncaught ReferenceError: check is not defined(…)

现在考虑另一种情况;

test.prototype.anotherFn=function()
{
var p=new Promise(function(){
this.check();
})
}

现在也出现同样的错误;

Uncaught ReferenceError: check is not defined(…)

调用时

var t=new test();
t.anotherFn();

最佳答案

check 函数在 prototypetest 对象。

当您像这样调用 nextFn 时:

t.nextfn();

随后的作用域将绑定(bind)到“type”testt 实例。在 nextfn 中访问 test 的原型(prototype)将通过 this 可用。

因此使用this访问check:

this.check();

这些东西可能会令人感到困惑。一个很好的引用是 this book .

====

对于你的第二个场景,问题是你正试图从一个有自己范围的函数中调用 this

JavaScript 中的作用域通常不是 block 作用域,而是函数作用域。它还有很多内容,我建议阅读有关闭包的教程以获得更全面的描述,但现在,试试这个:

test.prototype.anotherFn=function()
{
var self = this; // save reference to current scope
var p=new Promise(function(){
self.check(); // use self rather than this
})
}

关于javascript - 无法从Javascript中的另一个方法内部调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42115401/

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