Subj : Re: about defining object... To : netscape.public.mozilla.jseng From : celleris@naver.com (Youngsun Jeong) Date : Wed Oct 01 2003 09:50 pm Brendan Eich wrote in message news:<3F7B0C64.2090008@meer.net>... > 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. I modified that : } else { if(!JS_IsConstructing(cx)) { if(!js_ValueToObject(cx, argv[0], &obj)) return JS_FALSE; } } > > 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). Yes, I modified that. if (cx->fp->flags & JSFRAME_CONSTRUCTING) => if(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]. > obj = js_NewObject(cx, &my_class, NULL, NULL); if (!obj) return JS_FALSE; JS_SetPrivate(cx, obj, argv[0]); Is that right? And I tested my code. See below ; testscript : function sumage(age) { var myage = age.plusAge(10); //myage = age + 10 return myage; } "age" value is integer. But, it's not working. I got the error message "TypeError: age.plusAge is not a function". What is wrong? How "age" value is passed to function "plusAge()" *without* constructing myobject(that is "var myobj = new myobject();") *on the script*? .