Subj : Re: about defining object... To : Youngsun Jeong From : Brendan Eich Date : Wed Oct 01 2003 11:18 am Youngsun Jeong wrote: >And I write a native constructor: > >//native constructor >static JSBool >MyObj(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval >*rval) >{ > if(argc == 0) > { > obj = NULL; > > It seems better for your constructor to make a new object of your class, even when called with no arguments. > } > else > { > if(!js_ValueToObject(cx, argv[0], &obj)) > return JS_FALSE; > } > > This makes your constructor, whether called via new or not, convert its argument to an object and return that. That's wrong. If a script calls 'new myobject(42)', you should construct an object of my_class and give it an age, perhaps 42. In other words, you should call JS_IsConstructing(cx) (see below for more) early, and if not constructing (if not called via operator new), then consider doing an argument conversion. > if(!obj) > { > JS_ASSERT(!argc || JSVAL_IS_NULL(argv[0]) || >JSVAL_IS_VOID(argv[0])); > if (cx->fp->flags & JSFRAME_CONSTRUCTING) > return JS_TRUE; > > Again, you should *not* include "jscntxt.h" and use cx->fp or any other member. Use JS_IsConstructing(cx). > obj = js_NewObject(cx, &my_class, NULL, NULL); > > if (!obj) > return JS_FALSE; > > Here you can JS_SetPrivate to associate an age with the new obj. Perhaps the age can come from argv[0]. /be .