Re: How to check if a custom class has a private object set?

Till Schneidereit <[email protected]> Fri, 16 Dec 2016 14:53:12 +0100
Newsgroups gmane.comp.mozilla.devel.jseng
Message-ID <CACRHVk_JRZCe53BiKVfjuH6MFdh6mt7GoTPxDMvWei1nqypsPQ@mail.gmail.com>
On Fri, Dec 16, 2016 at 2:22 PM, Mihai Dobrescu <[email protected]>
wrote:

> I thonk the question could be rephrased like this:
>
> When a function is executed, being static, what is the meaning of the code
> below?
>
> JS::CallArgs args = CallArgsFromVp(argc, vp);
>
> JSObject* obj = &args.thisv().toObject();
>
> What is the content of obj?
>

Ok, that's what I thought was going on. `obj` in this case is the
constructor function for your class, not an instance of it.


>
> What is the outcome of JS_GetPrivate(obj)?
>

The assert you get in debug builds, or some random memory content in opt
builds because functions don't have a private slot.


>
> That obj won't have the required flag, but how could I tell that before?
>

By using JS_GetClass(obj) and ensuring that that matches your class. You
should do that regardless to ensure that everything works as expected.
Otherwise this will cause crashes:

// with your class C with instance function F() and static function S().
let someObj = {F: C.prototype.F};
someObj.F(); // Tries to use JS_GetPrivate on someObj, which isn't an
instance of C.