Search code examples
spidermonkey

Can a JS Object's constructor be written in C++ with SpiderMonkey?


I would like to implement a constructor for a Javascript Object in C++, using SpiderMonkey 38's API. But a constructor needs access to this (the JS Object being constructed) and the docs for JS::CallArgs say you mustn't call thisv() from a constructor, without suggesting any alternative. Does that mean it isn't actually possible to write a useful constructor in C++?


Solution

  • In C++ you just have to create the object that should be returned from the constructor yourself. (Nothing creates an initial object that would be accessible from this for your) Depending on what you need you should look into creating a new JSClass for that object.

    bool
    MyConstructor(JSContext* cx, unsigned argc, JS::Value* vp)
    {
      CallArgs args = CallArgsFromVp(argc, vp);
    
      JS::RootedObject obj(cx, JS_NewObject(cx, MyJSClass));
      if (!obj)
        return false;
    
      args.rval().setObject(*obj);
      return true;
    }