Javascript function()不是dojo中的函数

Javascript function()不是dojo中的函数,javascript,dojo,Javascript,Dojo,在dojo中调用函数时出现以下错误: TypeError:this.loadNameAndDescpFromLookup不是函数 但我不知道为什么 这是我的密码 readBarcodeFromMobile:function(){ stompClient.subscribe('/topic/messages',函数(事件){ registry.byId('PId').set(“value”,event.body); this.loadNameAndDescpFromLookup(event.bod

在dojo中调用函数时出现以下错误:

TypeError:this.loadNameAndDescpFromLookup不是函数

但我不知道为什么 这是我的密码

readBarcodeFromMobile:function(){
stompClient.subscribe('/topic/messages',函数(事件){
registry.byId('PId').set(“value”,event.body);
this.loadNameAndDescpFromLookup(event.body);//错误在这里
});
});
}            
loadNameAndDescpFromLookup:函数(条形码){}

有什么想法吗?

这里的问题是
这个

代码的一部分:

function(event) {
  if(registry.byId('productBarcodeId') != undefined){
    registry.byId('productBarcodeId').set("value", event.body);
    this.loadNameAndDescpFromLookup(event.body); // the error is here
  }
}
这里的
this
指的是
函数
,而不是您在其中编写整个代码的对象。 但是很明显,函数没有指定的dunction,因此会发生错误。


我真的不知道如何正确地做到这一点,但您可以使用一个变量来存储所需的上下文,并使用该变量而不是
this

例如:

#btn1,#btn2{
宽度:200px;
高度:200px;
}
工作
错误
init();
函数init(){
var currentThis=this;//此处此上下文的右侧存储在变量中
document.getElementById(“btn1”).onclick=function(){
currentThis.test();//这里的currentThis变量将用于查找正确的作用域
}
document.getElementById(“btn2”).onclick=function(){
this.test();//此处将发生错误
}
}
功能测试(){
警惕(“工作”);
}

正如其他人所指出的,问题在于
不引用您希望在函数内部使用的对象

解决方案是将
这个
上下文存储在变量中,稍后再引用它

比如说

readBarcodeFromMobile: function(){
const self = this; // save the `this` context in a variable
this.socket = SockJS('/controller/Barcode');
this.sockets.push(this.socket);
stompClient = Stomp.over(this.socket);
stompClient.connect({}, function(frame) {
    stompClient.subscribe('/topic/messages', function(event) {
      if(registry.byId('productBarcodeId') != undefined){
        registry.byId('productBarcodeId').set("value", event.body);
        self.loadNameAndDescpFromLookup(event.body); // use the stored context
      }
    });
 });
} 
loadNameAndDescpFromLookup: function(barcode){ }

function()
仍然是一个函数。问题是
指向了错误的上下文。“此”指向了窗口回调中的上下文(
)已更改。要维护外部上下文,可以使用箭头函数:
stompClient.connect({},(frame)=>{
等@Andy,但它与arrows@firstNamelastName查看下面我的答案。基本上-在变量中捕获
这个
,这样它就可以在函数中访问。有什么解决方案吗?
这里这是指函数
没有,它会指执行上下文。这不一定(也不经常)这将是回调函数本身。
这里的var currentThis将用于查找正确的作用域
,在本例中,这碰巧是由于某种意外情况而起作用的。
this
的值将是
窗口
。正如它所发生的那样
函数测试()
是一个隐含的全局变量,因此它会附加到
窗口
对象,因此为什么
this.test()
会起作用。如果代码被包装在IIFE中(通常情况下是这样的),这将不起作用。即使没有和iLife,当使用严格模式时,相同的代码也无法工作。@vlaz这就是为什么我注意到,我不知道如何正确地完成它,因为您似乎对这个主题有一些了解,请随时提供正确的解决方案。我不介意自己学习:)