Sunday 26 June 2016

javascript - Scoping Issue inside a function




I am having an issue with the scope of a variable. The first two return the correct value but when I subscribe to an event (the event is working) it returns this._id as undefined. I have also tried it as MyFunction._id;



 var i = 0;


var func = new MyFunction();
func.init();

function MyFunction(i){
this._id = i;
}

MyFunction.prototype.init = function(){

Debugger.log("A : " + this._id); //displays the result of i

this.myTest; //displays the result of i
Event.subscribe("UPDATE", this.myTest);// is undefined
}

MyFunction.prototype.myTest = function(){
Debugger.log("B : " + this._id);
}


Thx.



Answer



You have to do:



 Event.subscribe("UPDATE", this.myTest.bind(this));

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...