function()不是dojo中的函数

时间:2018-09-25 13:16:57

标签: javascript dojo

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

  

TypeError:this.loadNameAndDescpFromLookup不是函数

但是我不知道为什么?: 这是我的代码

readBarcodeFromMobile: function(){
        stompClient.subscribe('/topic/messages', function(event) {
            registry.byId('PId').set("value", event.body);
            this.loadNameAndDescpFromLookup(event.body); // the error is here
        });
    });
}            

loadNameAndDescpFromLookup: function(barcode){ }

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

就像其他人指出的那样,问题在于this并未引用您要在函数内部使用的对象。

解决方案是将this上下文存储在变量中,并在以后引用它。

例如

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){ }

答案 1 :(得分:0)

这里的问题是this

部分代码:

function(event) {
  if(registry.byId('productBarcodeId') != undefined){
    registry.byId('productBarcodeId').set("value", event.body);
    this.loadNameAndDescpFromLookup(event.body); // the error is here
  }
}

此处this是指function,而不是您在其中编写了整个代码的对象。 但是很明显,该函数没有指定的功能,因此会发生错误。


我不太确定如何正确执行此操作,但是您可以使用变量来存储所需的上下文并使用变量代替this

示例:

<head>
<style>
#btn1, #btn2 {
width: 200px;
height: 200px;
}
</style>
</head>
<Body>
<Button id="btn1">Working</Button>
<Button id="btn2">Error</Button>
<script>
init();
function init() {
	var currentThis = this; //Here the right this-context is stored in a variable
	document.getElementById("btn1").onclick = function() {
                  currentThis.test(); //here the var currentThis will be used to find the right scope
	}
        document.getElementById("btn2").onclick = function() {
                  this.test(); //Here an Error will occur
	}
}

function test() {
	alert("working");
}
</script>
</Body>