I’m attempting to make a class in javascript. I create it with the JSON type object thing.
Doing this:
Foo = {
PubId: '',
Init:function( oCallback )
{
this.sendCommand( 'INIT', {}, oCallback );
},
sendCommand : function( sCommand, aParams, oCallback )
{
setTimeout( oCallback, 1000, '{"response":"INIT","time":1287982024,"pubid":"4cc50bc47c7b3"}' );
return true;
},
onData : function( sData )
{
var aRes = JSON.parse( sData );
this.PubId = aRes.pubid;
alert( this.PubId );
return this.PubId;
},
umtest:function(){ alert( this.PubId ); }
}
I then also do this after including the script:
Foo.Init( Foo.onData );
The problem is that the this.PubId is updated inside the onData method, but outside of it, the pubid is empty.
I am pretty new at javascript classes, so I’m not sure what needs to be done so I was hoping someone could help meh out. 🙂
Thanks for your time!
Well you’ve got two problems here. The first problem is not understanding how
thisworks in Javascript. WhenFoo.onDatais called viasetTimeout( oCallback, ...)thethiswill reference to the global object notFoo.In order to call it with
Fooasthisyou should change your code:In order to test what’s changed place this code to
onData:In the updated version
thiswill correctly referenceFooas it’s object of invocation.The second problem you might be facing with is that your function called with
setTimeoutwill only be executed after1000 ms = 1s, so if you’re simply checkingalert(Foo.PubId)outside ofFooyou will get an empty string (because the callback hasn’t been called yet).In order to test if
Foo.PubIdis indeed changed:You can check the full test case here.