gpt4 book ai didi

javascript - 内部函数变量丢失外部函数的 'this' 值

转载 作者:行者123 更新时间:2023-12-03 05:34:55 25 4
gpt4 key购买 nike

我在 JavaScript 中创建了一个类,如下所示:

class TreeMatching
{
constructor()
{
this.thresholdPoints=0;
this.neighborWeight = 0.4;
this.totalFrequency = 0.0;
this.listSeq = [];
this.listFreq = [];
this.mapScore = new Object();
this.tree = new Trie();
}

createTree()
{
var list_Dictionary;
var loadWordList = $.get("../wordFrequencyTop5000.txt", function(data)
{
list_Dictionary = data.split("\n");
});

loadWordList.done(function()
{
for(var i=0;i<list_Dictionary.length;i++)
{
var string = list_Dictionary[i];
this.tree.insert(string); //<-- Cannot read property 'insert' of undefined
}
});

}
}

它应该调用 Trie 类中的 insert 方法,如下所示:

class Trie
{
constructor()
{
this.count=1;
this.root = new TrieNode();
}

insert(word)
{
var children = new Object();

for(var i=0; i<word.length(); i++){
var c = word.charAt(i);

var t;
if(children[c]){
t = children[c];
}else{
t = new TrieNode(c);
children.put(c, t);
}

children = t.children;

//set leaf node
if(i==word.length()-1)
t.isLeaf = true;
}
}
}

但是,标记错误的代码行,即外部函数的 this 值,没有属性 treemapScore 等。

有没有办法可以从内部回调函数访问这些值?

谢谢

最佳答案

look at 'this' - 您必须定义局部变量以在调用内维护对“this”的引用,如链接中所述。

createTree()
{
var self = this;
var list_Dictionary;
var loadWordList = $.get("../wordFrequencyTop5000.txt", function(data)
{
list_Dictionary = data.split("\n");
});

loadWordList.done(function()
{
for(var i=0;i<list_Dictionary.length;i++)
{
var string = list_Dictionary[i];
self.tree.insert(string); //<-- Now you should be able to do it
}
});

}

关于javascript - 内部函数变量丢失外部函数的 'this' 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40774978/

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