Subj : Re: [spidermonkey] JS_CallFunction in Finalize To : franck From : Brendan Eich Date : Fri Aug 26 2005 02:54 pm franck wrote: > Hello, > > Is it possible to call a js function on an object being Finalized ? It's possible, but it is not a good idea to let script get a reference to an object being finalized. If that reference escapes the callee into a global property or some other property of a live object, then scripts that use that reference later will crash and burn. Finalizers are *not* exposed to scripts for this reason, among others. Let's look at your example closely: > like this: > > > void Module_Finalize(JSContext *cx, JSObject *obj) { > > void *pv = JS_GetPrivate( cx, obj ); > if ( pv != NULL ) { > > jsval ret; > JS_CallFunctionName( cx, obj, "onClose", 0, NULL, &ret ); Aha! "Close" != "Finalize" -- do not mix them up. For one thing, you can hog resources and starve other uses of memory by doing so. It's up to the GC when to finalize. It is up to you or your users' code when to "Close". With a metaphor such as close (open/read/write/close), there usually is a mandatory call to close to flush buffers, release resources, and perhaps make GC'ed objects unreachable (therefore liable to be finalized at the GC's convenience). But all required prompt or eager flushing and releasing must come from a user-initiated close call. Of course, if a user forgets to close, but the object becomes garbage anyway, then its finalizer should flush/release as needed -- but that is not the norm, it's a user error that the system (or your part of it, not SpiderMonkey's and not your users' scripts) prevents from becoming a permanent leak or other bug. Consider DOM window objects. If I write , I shouldn't leak, but the opened window should be visually closed when the user clicks on its close [x] box or whatever widget is used by the desktop/window-manager/OS for closing windows, and at *that* point, "onunload" or a hypothetical "onclose" event handler should run -- *not* later when the window object is finalized by the GC. So you should probably say more about what this Module object's semantics and API are, at this point. Hope this helps. /be .