martinwells/objects.js

Classes not working with image load

Closed this issue · 3 comments

Hi,

My class converts from a class to a image when I do this.

https://gist.github.com/3116214

After the init, I load an image and set the imageHandlerWithin the class.

The console logs show the first log is still a class.

The 2nd console log shows that the class has become

Any idea how to work around this?

Alright, managed to hack it to work, basically the class loses its 'class' defination after a image.onload is passed to its functions. I stored a copy of the class before the class gets redefined, and then in the image handler I recreated the class using the stored instance. Kinda hacky but it worked.

Heres the fixed code

https://gist.github.com/3117761

The issue you're running into is actually a feature of Javascript. The this variable is an ever-changing variable managed by the javascript engine. Its value is equal to the context of the currently running code. (See http://unschooled.org/2012/03/understanding-javascript-this/)

In the case of your code, when the image is finished loading. The javascript engine will call the onload handler in the context of the image object (this.Class.nekoAnim). This means, that before your load handler is called, the JS engine sets the value of this to be equal to the nekoAnim object.

While the solution you came up with will work, it will also pollute the global name space and cause a race condition. The proper solution would be to use another feature of javascript called closures (also check out functional scope).

Hi,

Thanks for taking the time to explain,

yes I've ran into further issues after this but I've since swapped to preloading all assets before creating any classes that use the assets and that seems to have solved the problem.

Cheers