javascript context issue - parameters undefined

2020-04-16 02:32发布

问题:

I have this code:

targetMu: function(programmeCode, muId) {

//Parameter values are fine here

  targetMuController.targetMuView.on("targetMu:afterRender", function(programmeCode, muId) {       
        this.renderCustomWidgets(muId, programmeCode);
  });
}

When this.renderCustomWidgets(muId, programmeCode) gets fired, programmeCode & muId is undefined, why?

And how can I fix this?

回答1:

try to remove parameters from anonymous function:

targetMu: function(programmeCode, muId) {
    targetMuController.targetMuView.on("targetMu:afterRender", function() {       
        this.renderCustomWidgets(muId, programmeCode);
    });
}


回答2:

, function(programmeCode, muId) {

You just declared new parameters in the callback function with the same names.

Inside the callback, these names refer to the inner parameters – whatever was passed to the callback.